簡體   English   中英

在 init() 中使用 JavaFX Alert 時出現 IllegalStateException 因為不在 FX 應用程序線程上

[英]IllegalStateException when using JavaFX Alert in init() because not on FX application thread

使用這種方法,我正在嘗試為我的 JavaFX 應用程序實現一個應用程序預加載器。 我想在init()加載一些可能引發異常的重物,然后繼續start() 為了處理異常,我使用new Alert(AlertType.ERROR).showAndWait();顯示警報new Alert(AlertType.ERROR).showAndWait(); 向用戶顯示一些細節。

public class Test extends Application {
    @Override
    public void init() throws Exception {
        try {
            // dome some heavy stuff here
            throw new Exception();
        } catch (Exception e) {
            new Alert(AlertType.ERROR).showAndWait();
            Platform.exit();
        }
    }

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

但這會導致警報未顯示並生成以下堆棧跟蹤(請參閱此處的完整堆棧跟蹤):

Exception in Application init method
java.lang.reflect.InvocationTargetException
    ... 
Caused by: java.lang.RuntimeException: Exception in Application init method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:895)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = JavaFX-Launcher
    at javafx.graphics/com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:291)
    ...
    at javafx.controls/javafx.scene.control.Alert.<init>(Alert.java:222)
    at src/gui.Test.init(Test.java:18)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:824)
    ... 2 more
Exception running application gui.Test

但是,如果我將嚎叫代碼從init()start()我的方法就可以正常工作。

過去,我已經能夠通過將邏輯包裝在 Platform.runLater() 調用中來解決此類問題。 IE:

try {
    [...]
}  catch (Exception e) {
    Platform.runLater(new Runnable() {
    @Override public void run() {
        new Alert(AlertType.ERROR).showAndWait();
        Platform.exit();
    });
}

每次我需要做一些與界面中發生的事情沒有直接關系的工作時,我都會使用這種方法。

取自維基:

public static void runLater(Runnable runnable)
參數:
runnable - 其運行方法將在 JavaFX 應用程序線程上執行的 Runnable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM