繁体   English   中英

JavaFX警报对话框取消按钮

[英]JavaFX Alert Dialog Cancel Button

我制作了一个JavaFX警报对话框来提示用户,询问他们是否要在关闭应用程序之前保存控制台的输出。

我有是,没有选择的照顾。 如果用户单击“取消”,我希望它仅关闭对话框并使所有内容保持打开状态。 截至目前,如果我点击取消,它将关闭GUI。

这是我的代码,用于覆盖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)
            {

            }  
        }
    });

“ yesButton”和“ cancelButton”中的if块都使用CloseRequest WindowEvent

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

使用Platform.exit()代替System.exit(0)

onCloseRequest文档中

当有外部请求关闭此窗口时调用。 已安装的事件处理程序可以通过使用接收到的事件来防止窗口关闭。

请注意,如果用户关闭警报对话框而不按任何按钮,则result.get()将引发异常。 对话框文档对此进行了详尽的解释。

使用primaryStage.close(); 而不是System.exit(0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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