英文:
what event is fired when you close a javafx application from the task bar and how do you handle it?
问题
我看过一些关于这个问题的帖子,即使其中有些答案被标记为正确,但它们似乎并不起作用,可能有许多原因。
我想要的是,在用户通过右键单击应用程序关闭应用程序时,能够处理这个事件。我想要处理这个事件,以确保干净地关闭应用程序,并确保保存所有用户数据。
我尝试过添加一个关闭钩子(示例如下),但在从任务栏关闭应用程序时,它并没有被触发。
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.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论