JavaFX:阶段关闭处理程序 [英] JavaFX: Stage close handler

查看:1131
本文介绍了JavaFX:阶段关闭处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to save a file before closing my JavaFX application.

这就是我在 Main :::中设置处理程序的方法开始

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

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

And the controller calling Stage::close when a button is pressed:

@FXML
public void exitApplication(ActionEvent event) {
    ((Stage)rootPane.getScene().getWindow()).close();
}

如果我关闭窗口,点击窗口边框上的红色X(正常情况下)方式)然后我得到输出消息舞台正在关闭,这是所需的行为。

If I close the window clicking the red X on the window border (the normal way) then I get the output message "Stage is closing", which is the desired behavior.

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

However, when calling Controller::exitApplication the application closes without invoking the handler (there's no output).

我怎么能让控制器使用我添加到 primaryStage的处理程序

How can I make the controller use the handler I've added to primaryStage?

推荐答案

如果你看一下生命周期 应用程序类:


JavaFX运行时执行以下操作,订单,每当启动
应用程序时:

The JavaFX runtime does the following, in order, whenever an application is launched:


  1. 构造指定Application类的实例

  2. 调用 init()方法

  3. 调用 start(javafx.stage.Stage)方法

  4. 等待应用程序完成,这发生在发生以下情况:


    • 应用程序调用 Platform.exit()

    • 最后一个窗口已关闭,平台上的 implicitExit 属性为 true

  1. Constructs an instance of the specified Application class
  2. Calls the init() method
  3. Calls the start(javafx.stage.Stage) method
  4. Waits for the application to finish, which happens when either of the following occur:
    • the application calls Platform.exit()
    • the last window has been closed and the implicitExit attribute on Platform is true


这意味着您可以调用 Platform.exit()在您的控制器上:

This means you can call Platform.exit() on your controller:

@FXML
public void exitApplication(ActionEvent event) {
   Platform.exit();
}

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

as long as you override the stop() method on the main class to save the file.

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

如你所见,通过使用 stop()您不再需要侦听关闭请求来保存文件(如果您想阻止关闭窗口,可以这样做。)

As you can see, by using stop() you don't need to listen to close requests to save the file anymore (though you can do it if you want to prevent window closing).

这篇关于JavaFX:阶段关闭处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆