阻止或取消退出JavaFX 2

时间:2012-12-05 16:00:36

标签: window javafx-2

退出JavaFX程序时,我会覆盖Application.stop()以检查未保存的更改。这样可以,但是给用户提供取消操作的选项会很好。

1 个答案:

答案 0 :(得分:19)

Application.stop()是最后的机会,换句话说,虽然它确实陷入退出,但撤销退出流程有点迟。

最好是设置一个关闭请求的监听器,可以通过使用该事件来取消。

在应用程序类中:

public void start(Stage stage) throws Exception {
    FXMLLoader ldr = new FXMLLoader(getClass()
                .getResource("Application.fxml"));
    Parent root = (Parent) ldr.load();
    appCtrl = (ApplicationController) ldr.getController();

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();

    scene.getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent ev) {
            if (!appCtrl.shutdown()) {
                ev.consume();
            }
        }
    });
}

然后在应用程序控制器中,上面引用为appCtrl

/** reference to the top-level pane                               */
@FXML
private AnchorPane mainAppPane;

public boolean shutdown() {
    if (model.isChanged()) {
        DialogResult userChoice =
                ConfirmDialog.showYesNoCancelDialog("Changes Detected",
                "Do you want to save the changes?  Cancel revokes the "
                + "exit request.",
                mainAppPane.getScene().getWindow());

        if (userChoice == DialogResult.YES) {
            fileSave(null);

            if (model.isChanged()) {
                // cancelled out of the save, so return to the app
                return false;
            }
        }

        return userChoice == DialogResult.NO;
    }

    return true;
}

注意:FXML中引用了mainAppPane(在本例中使用JavaFX Scene Builder)以允许访问场景和窗口;该对话框是从https://github.com/4ntoine/JavaFxDialog扩展而来的,而fileSave是File的文件的事件处理程序 - &gt;保存菜单项。对于文件 - &gt;退出菜单项:

@FXML
private void fileExitAction(ActionEvent ev) {
    if (shutdown()) {
        Platform.exit();
    }
}

希望这有助于某人!

相关问题