I have tried the below code, it works fine with mouse event, but when I use key event i.e ENTER Key on any button than its not showing the result.
Alert aler
I do not recommend making all buttons respond to enter, as that is counter to how most UI dialogs work.
Normally, a button with focus will fire when you press space, not enter. There are however special buttons that will activate on specific keys: A default button will fire on enter and a cancel button will fire on esc. Usually you will have only one of each of these special types of buttons in your dialog, so that they can be fired via the special keyboard accelerator, regardless of which button currently has focus.
Additionally, different desktop OS systems have different standards on placement of default and cancel buttons in a dialog system. This is to assist the user in easily finding these special buttons in any dialog. The JavaFX dialog system implements some logic internally for locating buttons in dialogs where the user would expect to see them across different desktop operating systems.
Let's say you want the button types from your example to be defined as default or cancel buttons and placed in the correct position for such buttons for your OS, then you can do as below:
ButtonType buttonTypeTwo = new ButtonType(
"Two",
ButtonBar.ButtonData.OK_DONE
);
ButtonType buttonTypeThree = new ButtonType(
"Three",
ButtonBar.ButtonData.CANCEL_CLOSE
);
Note the JavaFX system has automatically changed the position of the buttons and some of the color highlighting. When the user presses enter, then "Two" will fire, when the user presses esc, then "Three" will fire. If you run the same code on Windows or Linux, likely the buttons will be positioned differently, according to whatever button positioning standard is used for those OSes.
If you don't want JavaFX to reposition your buttons according to OS standards, but you want them to still respond to enter and esc keys, then you can lookup the buttons and directly modify the button attributes like below:
Button buttonTwo = (Button) alert.getDialogPane().lookupButton(buttonTypeTwo);
buttonTwo.setDefaultButton(true);
Button buttonThree = (Button) alert.getDialogPane().lookupButton(buttonTypeThree);
buttonThree.setCancelButton(true);
I recommend letting JavaFX appropriately position buttons of specific types rather than performing lookups as above.
I also recommend setting at least a CANCEL_CLOSE button or OK_DONE button in your JavaFX Alert, otherwise the user may have a difficult time actually closing the alert as the dialog will probably not respond to key presses as the user expects.