简体   繁体   中英

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>()
    {
        @Override
        public void handle(WindowEvent event)
        {
            Alert alert = new Alert(AlertType.WARNING);
            alert.setTitle("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)
            {
                Main.setConsoleVisible();
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            else if(result.get() == noButton)
            {
                System.exit(0);
            }
            else if(result.get() == cancelButton)
            {

            }  
        }
    });

Both in "yesButton" and "cancelButton" if-blocks consume the CloseRequest WindowEvent :

else if(result.get() == cancelButton)
{
    event.consume();
}

Use Platform.exit() instead of System.exit(0) .

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.

Use primaryStage.close(); instead of System.exit(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM