什么事件会在从任务栏关闭 JavaFX 应用程序时触发,以及如何处理它?

huangapple go评论79阅读模式
英文:

what event is fired when you close a javafx application from the task bar and how do you handle it?

问题

我看过一些关于这个问题的帖子,即使其中有些答案被标记为正确,但它们似乎并不起作用,可能有许多原因。

什么事件会在从任务栏关闭 JavaFX 应用程序时触发,以及如何处理它?

我想要的是,在用户通过右键单击应用程序关闭应用程序时,能够处理这个事件。我想要处理这个事件,以确保干净地关闭应用程序,并确保保存所有用户数据。

我尝试过添加一个关闭钩子(示例如下),但在从任务栏关闭应用程序时,它并没有被触发。

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    System.out.println("closing . . .");
}));

我尝试的另一种方法是为我的舞台添加一个setOnCloseRequest监听器,如下所示,但是在从任务栏关闭应用程序时,WINDOW_CLOSE_REQUEST事件也没有被触发。

stage.setOnCloseRequest(event2 -> {
    System.out.println("closing . . .");
    Platform.exit();
    System.exit(0);
});
英文:

I've seen a few posts about this that have answers marked as correct even though they don't seem to work for which could be for a number of reasons.

什么事件会在从任务栏关闭 JavaFX 应用程序时触发,以及如何处理它?

What I would like is to handle the event in which the user closes the application from the taskbar by right-clicking on the application, I would like to handle this to ensure a clean shutdown and to make sure all user data is saved.

I have tried adding a shutdown hook (example below) but that wasn't triggered when closing the application from the taskbar

Runtime.getRuntime().addShutdownHook(new Thread(()->{
    System.out.println("closing . . .");
}));

The other method I tried was to add a setOnCloseRequest listener for my stage as shown below but the WINDOW_CLOSE_REQUEST event also wasn't fired when closing the application form the taskbar.

stage.setOnCloseRequest(event2 -> {
   System.out.println("closing . . .");
   Platform.exit();
   System.exit(0);
});

答案1

得分: 0

基于 @James_D 的回答,我意识到我在错误的地方添加了关闭钩子。为了帮助其他相对新手的 Java 和 JavaFX 开发者,在主方法中调用 launch(args) 之前必须添加关闭钩子。

英文:

Based on @James_D's response I realized I was adding the shutdown hook in the incorrect place, to help anyone else who is relatively new to java and JavaFX when adding a shutdown hook you must do it before calling launch(args) in the main method.

huangapple
  • 本文由 发表于 2020年5月2日 18:25:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61557800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定