JavaFX alert with aditional buttons

Viewed 39

I need an alert with 2 buttons: yes and no. I created the alert with:

alert.getDialogPane().getButtonTypes().clear();
ButtonType yesButtonType = new ButtonType("Yes", ButtonBar.ButtonData.YES);
ButtonType noButtonType = new ButtonType("No", ButtonBar.ButtonData.NO);
alert.getDialogPane().getButtonTypes().add(yesButtonType);
alert.getDialogPane().getButtonTypes().add(noButtonType);

Optional<ButtonType> result = alert.showAndWait();

But when I try to handle the action for every button with:

if (result.isPresent() && result.get() == ButtonType.YES) {
    System.out.println("OK");
}

It does not work. Any idea why?

1 Answers

== is an instance comparison and you are creating a new instance, so the comparison fails.

Instead of creating new button types, reuse the existing predefined types:

alert.getDialogPane().getButtonTypes().setAll(
    ButtonType.YES, 
    ButtonType.NO
);
Related