簡體   English   中英

java.lang.IllegalStateException: 不在 FX 應用程序線程上; 當前線程 = 線程 4

[英]java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

我正在嘗試從 Thread 設置 Text 對象的字符串,但它給了我這個錯誤:

Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.needsTextLayout(Unknown Source)
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source)
at javafx.scene.text.Text.access$200(Unknown Source)
at javafx.scene.text.Text$2.invalidated(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.scene.text.Text.setText(Unknown Source)
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70)

處理程序類:

@FXML
private Text timer;

@Override
public void initialize(URL url, ResourceBundle rb) {
    init();
    new Thread() {
        public void run() {
            while(true) {
                Calendar cal = new GregorianCalendar();

                int hour = cal.get(cal.HOUR);
                int minute = cal.get(cal.MINUTE);
                int second = cal.get(cal.SECOND);
                int AM_PM = cal.get(cal.AM_PM);

                String time = hour + "" + minute + "" + second;
                timer.setText(time);
            }
        }
    }.start();
}

我正在學習教程 教程中的那個人沒有使用 JavaFX。

我曾嘗試使用Platform.runLater() ,它確實有效,但它使我的程序崩潰。 我還嘗試在Platform.runLater(new Runnable() { })方法上創建一個計時器,但它給了我與以前相同的錯誤。

timer.setText()包裹在Platform.runLater() 在它之外,在 while 循環內,添加Thread.sleep(1000);

Illegal State Exception 背后的原因是您試圖在 JavaFX 應用程序線程以外的某個線程上更新 UI。

您的應用程序在添加時崩潰的原因是您通過添加要在 UI 線程上無限執行的進程來使 UI 線程過載。 讓線程休眠 1000 毫秒將幫助您解決這個問題。

如果可能,將 while(true) 替換為 Timer 或 TimerTask。

有關更多選項,請點擊此鏈接

暫無
暫無

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

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