JavaFX:阶段关闭处理程序

Hei*_*ade 45 java javafx handler javafx-8

我想在关闭JavaFX应用程序之前保存文件.

这就是我在以下方式设置处理程序的方式Main::start:

primaryStage.setOnCloseRequest(event -> {
    System.out.println("Stage is closing");
    // Save file
});
Run Code Online (Sandbox Code Playgroud)

Stage::close当按下按钮时控制器调用:

@FXML
public void exitApplication(ActionEvent event) {
    ((Stage)rootPane.getScene().getWindow()).close();
}
Run Code Online (Sandbox Code Playgroud)

如果我关闭窗口,单击窗口边框上的红色X(正常方式),然后我得到输出消息" Stage is closing",这是所需的行为.

但是,在调用Controller::exitApplication应用程序时关闭而不调用处理程序(没有输出).

如何让控制器使用我添加的处理程序primaryStage

Jos*_*eda 86

如果你看一下在生命周期中的Application类:

无论何时启动应用程序,JavaFX运行时都会按顺序执行以下操作:

  1. 构造指定Application类的实例
  2. 调用init()方法
  3. 调用start(javafx.stage.Stage)方法
  4. 等待应用程序完成,当发生以下任一情况时会发生:
    • 应用程序调用 Platform.exit()
    • 最后一个窗口已关闭,implicitExit属性Platformtrue
  5. 调用stop()方法

这意味着您可以呼叫Platform.exit()您的控制器:

@FXML
public void exitApplication(ActionEvent event) {
   Platform.exit();
}
Run Code Online (Sandbox Code Playgroud)

只要覆盖stop()主类上的方法来保存文件.

@Override
public void stop(){
    System.out.println("Stage is closing");
    // Save file
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,通过使用stop()您不再需要监听关闭请求来保存文件(尽管如果您想要阻止窗口关闭,您可以这样做).


Dom*_*ico 8

假设您想询问用户是否要退出应用程序而不保存工作。如果用户选择否,则无法避免应用程序在 stop 方法中关闭。在这种情况下,您应该为 WINDOW_CLOSE_REQUEST 事件向窗口添加一个 EventFilter

在您的 start 方法中添加此代码以检测事件:

(请注意,调用 Platform.exit(); 不会触发 WindowEvent.WINDOW_CLOSE_REQUEST 事件,请参阅下文以了解如何从自定义按钮手动触发事件)

// *** Only for Java >= 8 ****
// ==== This code detects when an user want to close the application either with
// ==== the default OS close button or with a custom close button ====

primaryStage.getScene().getWindow().addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, this::closeWindowEvent);
Run Code Online (Sandbox Code Playgroud)

然后添加您的自定义逻辑。在我的示例中,我使用 Alert 弹出窗口询问用户他/她是否想在不保存的情况下关闭应用程序。

private void closeWindowEvent(WindowEvent event) {
        System.out.println("Window close request ...");

        if(storageModel.dataSetChanged()) {  // if the dataset has changed, alert the user with a popup
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.getButtonTypes().remove(ButtonType.OK);
            alert.getButtonTypes().add(ButtonType.CANCEL);
            alert.getButtonTypes().add(ButtonType.YES);
            alert.setTitle("Quit application");
            alert.setContentText(String.format("Close without saving?"));
            alert.initOwner(primaryStage.getOwner());
            Optional<ButtonType> res = alert.showAndWait();

            if(res.isPresent()) {
                if(res.get().equals(ButtonType.CANCEL))
                    event.consume();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

event.consume()方法可防止应用程序关闭。显然,您应该至少添加一个允许用户关闭应用程序的按钮,以避免用户强制关闭应用程序,这在某些情况下可能会损坏数据。

最后,如果您必须从自定义关闭按钮触发事件,您可以使用:

Window window = Main.getPrimaryStage()  // Get the primary stage from your Application class
                .getScene()
                .getWindow();

window.fireEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSE_REQUEST));
Run Code Online (Sandbox Code Playgroud)