Since jdk 8u40, I'm using the new javafx.scene.control.Alert
API to display a confirmation dialog. In the example below, "Yes" button is focused by default instead of "No" button:
public boolean showConfirmDialog(String title, String header, String content, AlertType alertType) {
final Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);
alert.getButtonTypes().clear();
alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
final Optional<ButtonType> result = alert.showAndWait();
return result.get() == ButtonType.YES;
}
And I don't know how to change it.
EDIT :
Here a screenshot of the result where "Yes" button is focused by default :
A simple function thanks to crusam:
Usage:
I am not sure if the following is the way to usually do this, but you could change the default button by looking up the buttons and setting the default-behavior yourself:
If you have a look at (private)
ButtonBarSkin
class, there is a method calleddoButtonOrderLayout()
that performs the layout of the buttons, based in some default OS behavior.Inside of it, you can read this:
Since
ButtonType.YES
is the default button, it will be the one focused.So @ymene answer is correct: you can change the default behavior and then the one focused will be
NO
.Or you can just avoid using that method, by setting
BUTTON_ORDER_NONE
in thebuttonOrderProperty()
. Now the first button will have the focus, so you need to place first theNO
button.Note that
YES
will still have the default behavior: This meansNO
can be selected with the space bar (focused button), whileYES
will be selected if you press enter (default button).Or you can change also the default behavior following @crusam answer.