JavaFX alert dialog ignores focused button
Why is the JavaFX warning dialog triggering Platform.exit (); when i press enter even if the focused button in the alert dialog is canceled?
soaStage.setOnCloseRequest(new EventHandler<WindowEvent>()
{
@Override
public void handle(WindowEvent event)
{
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirm");
alert.setHeaderText("Are you sure you want to exit?");
alert.setContentText("Press OK to exit, or Cancel to stay.");
alert.initOwner(soaStage);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK)
{
Platform.exit();
}
else
{
event.consume();
}
}
});
source to share
The default buttons run on enter
The OK button will be clicked when you click enter, because this is the default button .
The default button is a button that receives the VK_ENTER keyboard if no other node in the scene is using it.
In the JavaFX 8 Modena standard stylesheet, the button is listed as blue by default, rather than the gray of the standard button.
How to remove the default button behavior
You can remove this behavior from the alert dialog without making the OK button the default button:
Button okButton = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
okButton.setDefaultButton(false);
I advise you not to do this, but instead always leave the default button on alert dialogs.
In OS X, the standard alert type dialogs have a default button that is triggered by entereven if the other button is focused, so the standard behavior in JavaFX is consistent with this. Note. To enable this behavior in the default dialog box in OS X, Full Keyboard Access must be enabled .
If you changed the OK button to not be the default button, I suggest you change its text to something else (for example, Exit for your case):
okButton.setText("Exit");
How to make enterbacklit buttons
Now, if you also want to make the focused button fire on click enter, you can do this:
EventHandler<KeyEvent> fireOnEnter = event -> {
if (KeyCode.ENTER.equals(event.getCode())
&& event.getTarget() instanceof Button) {
((Button) event.getTarget()).fire();
}
};
DialogPane dialogPane = alert.getDialogPane();
dialogPane.getButtonTypes().stream()
.map(dialogPane::lookupButton)
.forEach(button ->
button.addEventHandler(
KeyEvent.KEY_PRESSED,
fireOnEnter
)
);
Note. In any case, the focused buttons always fire when pressed space.
source to share
We can add binding ENTERto all buttons by creating a class that needs to be created once when the application starts.
public class EnableButtonEnterKey extends ButtonBehavior<Button> {
public EnableButtonEnterKey() {
super(new Button());
BUTTON_BINDINGS.add(new KeyBinding(ENTER, KEY_PRESSED, "Press"));
BUTTON_BINDINGS.add(new KeyBinding(ENTER, KEY_RELEASED, "Release"));
}
}
When starting the application, call
new EnableButtonEnterKey();
What is it.
source to share