JavaFX:退出前确认(X按钮)

时间:2018-08-12 19:00:47

标签: javafx

我需要在关闭应用程序之前显示警报确认(按X键)

public void start(Stage primaryStage) throws Exception {
    this.primaryStage = primaryStage;
    ...
    primaryStage.setOnHiding(event -> {
        System.out.println("hidding");
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION, Lang.getString("exit_confirmation"));
        Toolkit.getDefaultToolkit().beep();
        Optional<ButtonType> result = alert.showAndWait();

        if (result.isPresent() && result.get() != ButtonType.OK) {
            return;
            //don't close stage
        }
    });
}

但是无论如何primaryStage已关闭。仅在按下ButtonType.OK时才能如何编码才能退出应用程序?对不起,我的英语

1 个答案:

答案 0 :(得分:2)

最好先搜索问题,以找到更好的解释,但这是您的答案

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
         //your code goes here


         //this line cancel the close request
         event.consume();
    }
});