Vic*_*rte 18 java javafx javafx-2
我在关闭我的javaFX应用程序时遇到问题,当我点击我的舞台上的关闭按钮时,我的应用程序消失但是如果我在我的任务管理器中查找它,我的应用程序仍然没有关闭.我试图使用下面的代码强制它关闭主线程和所有子线程,但问题仍然存在.
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
Platform.exit();
}
});
Run Code Online (Sandbox Code Playgroud)
Sea*_*man 24
您的应用程序是否产生任何子线程?如果是这样,你确保你终止它们(假设它们不是守护程序线程)?
如果您的应用程序生成非守护程序线程,那么它们(以及您的应用程序)将继续存在,直到您终止该进程为止
Vic*_*rte 21
唯一的方法是调用System.exit(0);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
Run Code Online (Sandbox Code Playgroud)
[EDITED]
System.exit将隐藏您的应用程序,如果您打开SO的管理器任务,您的应用程序将在那里.正确的方法是逐个检查你的线程,并在关闭应用程序之前关闭所有线程.
public void start(Stage stage) {
Platform.setImplicitExit(true);
stage.setOnCloseRequest((ae) -> {
Platform.exit();
System.exit(0);
});
}
Run Code Online (Sandbox Code Playgroud)
我能够通过调用来解决这个问题com.sun.javafx.application.tkExit()
.您可以在我的其他答案中阅读更多内容:https://stackoverflow.com/a/22997736/1768232(这两个问题确实是重复的).
我在控制器中使用ThreadExecutor时遇到此问题.如果ThreadExecutor未关闭,则应用程序不会退出.请参阅此处: 如何关闭所有执行程序 - 何时退出应用程序
由于识别控制器中的应用程序退出可能是一个问题,因此可以从Application类中获取对控制器的引用(使用Eclipse中的示例应用程序):
public class Main extends Application {
private SampleController controller;
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
BorderPane root = (BorderPane)loader.load(getClass().getResource("Sample.fxml").openStream());
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
controller = loader.<SampleController>getController();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序会覆盖stop方法,您可以在其中调用控制器的内务处理方法(我使用一种名为startHousekeeping的方法):
/**
* This method is called when the application should stop,
* and provides a convenient place to prepare for application exit and destroy resources.
*/
@Override
public void stop() throws Exception
{
super.stop();
if(controller != null)
{
controller.startHousekeeping();
}
Platform.exit();
System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)