I want to give the buttons "OK" and "Cancel" a method, which will be execute, when the user clicks on one of these buttons:
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());
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
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With