Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a method to a JavaFX Alert Button

Tags:

java

javafx

alert

I want to give the buttons "OK" and "Cancel" a method, which will be execute, when the user clicks on one of these buttons:

Alert Box

How can I do this with my code?

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Test");
alert.setHeaderText("This is a test.");
alert.setResizable(false);
alert.setContentText("Select okay or cancel this alert.");
alert.showAndWait();

In my theory, the code to set an action for one of the buttons looks like this:

alert.setActionForButtonOK(OkMethod());
like image 371
Julian Schmuckli Avatar asked Dec 08 '22 18:12

Julian Schmuckli


2 Answers

The alert#showAndWait returns an Optional containing the button that has been pressed (or null if the no button has been pressed and the dialoge is exited). Use that result to choose which operation you would like to run. E.g.

Optional<ButtonType> result = alert.showAndWait();
if(!result.isPresent())
    // alert is exited, no button has been pressed.
else if(result.get() == ButtonType.OK)
     //oke button is pressed
else if(result.get() == ButtonType.CANCEL)
    // cancel button is pressed
like image 86
n247s Avatar answered Dec 10 '22 09:12

n247s


There is no need to register event handlers to the button (and btw the Dialog class is not designed to provide direct access to it's buttons). You can simply check the value returned by showAndWait to get the button that was pressed by the user and act accordingly:

Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Test");
alert.setHeaderText("This is a test.");
alert.setResizable(false);
alert.setContentText("Select okay or cancel this alert.");

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

if (button == ButtonType.OK) {
    System.out.println("Ok pressed");
} else {
    System.out.println("canceled");
}
like image 35
fabian Avatar answered Dec 10 '22 07:12

fabian