java fx 关闭窗口提示“你确定要关闭吗”

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34651026/article/details/88873900

很容易直接上代码

 //为当前窗口添加关闭监听
Stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                //对话框 Alert Alert.AlertType.CONFIRMATION:反问对话框
                Alert alert2 = new Alert(Alert.AlertType.CONFIRMATION);
                //设置对话框标题
                alert2.setTitle("Exit");
                 //设置内容
                alert2.setHeaderText("Are you sure to exit");
                //显示对话框
                Optional<ButtonType> result = alert2.showAndWait();
                //如果点击OK
                if (result.get() == ButtonType.OK){
                    // ... user chose OK
                    Stage.close();
                //否则
                } else {
                    event.consume();
                }
            }
        });

补充:Alert.AlertType:

             AlertType.INFORMATION   //信息对话框

            AlertType.WARNING            // 警告对话框

            AlertType.ERROR                //错误对话框

猜你喜欢

转载自blog.csdn.net/qq_34651026/article/details/88873900
FX