一尘不染

java.lang.IllegalStateException:不在FX应用程序线程上;currentThread =线程4

java

我正在尝试从线程中设置文本对象的字符串,但这给了我这个错误:

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();
}

我尝试使用Platform.runLater(),它确实可以工作,但是它使我的程序崩溃。我也尝试在该Platform.runLater(new Runnable() { })方法上创建一个Timer,但它给了我与以前相同的错误。


阅读 703

收藏
2020-03-23

共1个答案

一尘不染

timer.setText()起来Platform.runLater()。在它的外面,在while循环中,添加Thread.sleep(1000);

非法状态异常的原因是你试图在JavaFX Application线程以外的其他线程上更新UI。

添加应用程序时崩溃的原因是,通过无限期添加要在UI线程上执行的进程,UI线程过载。使线程hibernate1000ms将有助于你解决此问题。

如果可能,用Timer或TimerTask替换while(true)。

2020-03-23