JavaFX应用程序在关闭后仍然运行

我在关闭我的javaFX应用程序时遇到问题,当我点击我的舞台上的关闭按钮时,我的应用程序消失但是如果我在我的任务管理器中查找它,我的应用程序仍然没有关闭。 我试图使用下面的代码强制它关闭主线程和所有子线程,但问题仍然存在。

primaryStage.setOnCloseRequest(new EventHandler() { @Override public void handle(WindowEvent t) { Platform.exit(); } }); 

您的应用程序是否会生成任何子线程? 如果是这样,你确保你终止它们(假设它们不是守护程序线程)?

如果您的应用程序生成非守护程序线程,那么它们(以及您的应用程序)将继续存在,直到您终止该进程为止

唯一的方法是调用System.exit(0);

 primaryStage.setOnCloseRequest(new EventHandler() { @Override public void handle(WindowEvent t) { Platform.exit(); System.exit(0); } }); 

[EDITED]

System.exit将隐藏您的应用程序,如果您打开SO的管理器任务,您的应用程序将在那里。 正确的方法是逐个检查你的线程,并在关闭应用程序之前关闭所有线程。

首先看这里

  public void start(Stage stage) { Platform.setImplicitExit(true); stage.setOnCloseRequest((ae) -> { Platform.exit(); System.exit(0); }); } 

我通过调用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.getController(); } catch(Exception e) { e.printStackTrace(); } } 

您的应用程序会覆盖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); } 

只是注意:尝试检查您是否使用

 Platform.setImplicitExit(false); 

有一个类似的问题,溢出我的任务。 上面的行不会让舞台关闭,它会隐藏它。

要模仿按’x’可以做:

 stage.fireEvent(new WindowEvent(stage, WindowEvent.WINDOW_CLOSE_REQUEST)) 

您可以通过单击关闭按钮关闭应用程序,并使用一些代码。

  stage.setOnCloseRequest( event -> closeMyApp() ); private void closeMyApp() { try { Stage stage = (Stage) closeButton.getScene().getWindow(); stage.close(); } catch(Exception ee) { ex.printStackTrace(); } } // where closeButton is button having similar controller class initialization. @FXML private Button closeButton;