我有一个JavaFX应用程序,可以同时打开多个窗口。其中一些窗口也能够产生"对话框"视窗。同时,应用程序在后台检查某些条件,并立即调用Platform.exit()
来终止整个应用程序。
我创建了一个迷你样本,展示了如何发生这种情况。
public class test extends Application {
@Override
public void start(final Stage primaryStage) throws Exception {
final VBox root = new VBox();
final Scene sc = new Scene(root);
primaryStage.setScene(sc);
primaryStage.show();
// Platform.runLater is necessary because this start() must not be blocked
Platform.runLater(() -> {
final Button button = new Button("Exit");
button.setOnAction(e -> Platform.exit());
Stage st = new Stage();
st.setScene(new Scene(button));
st.initOwner(primaryStage);
st.initModality(Modality.WINDOW_MODAL); // Just need window-level modality
st.showAndWait(); // Shows the "dialog" window
});
}
public static void main(final String[] args) {
Application.launch(args);
}
}
单击按钮时抛出的异常:
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = JavaFX Application Thread
at com.sun.glass.ui.Application.checkEventThread(Application.java:443)
at com.sun.glass.ui.Application.isNestedLoopRunning(Application.java:544)
at com.sun.javafx.tk.quantum.QuantumToolkit.isNestedLoopRunning(QuantumToolkit.java:1139)
at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:585)
at javafx.stage.Stage.showAndWait(Stage.java:474)
at test.lambda$0(test.java:43)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
如何确保Platform.exit()
的安全通话?