DrZoo DrZoo - 1 year ago 325
Java Question

JavaFX Alert Dialog Cancel Button

I made a JavaFX alert dialog box to prompt the user, asking if they want to save the output from the console before closing the application.

I have the yes and no options taken care of. If the user clicks cancel, I want it to just close the dialog box and leave everything open. As of right now, if I hit cancel it will close the GUI.

Here is my code for overriding the close button on the GUI.

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
public void handle(WindowEvent event)
Alert alert = new Alert(AlertType.WARNING);
alert.setHeaderText("Would You Like To Save Your Console Output?");
alert.setContentText("Please choose an option.");

ButtonType yesButton = new ButtonType("Yes");
ButtonType noButton = new ButtonType("No");
ButtonType cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);

alert.getButtonTypes().setAll(yesButton, noButton, cancelButton);

Optional<ButtonType> result = alert.showAndWait();
if(result.get() == yesButton)
else if(result.get() == noButton)
else if(result.get() == cancelButton)


Answer Source

From the documentation for onCloseRequest:

Called when there is an external request to close this Window. The installed event handler can prevent window closing by consuming the received event.

Be aware that result.get() will throw an exception if the user closes the alert dialog without pressing any buttons. The Dialog documentation explains this thoroughly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download