计时器错误java.lang.IllegalStateException

时间:2014-02-10 10:06:24

标签: java multithreading exception timer

我试图在JRE 8中显示一个标签,说明所有内容都只有3秒,因为我无法在JRE 7中使用DatePicker而且我发现了这个错误。

    Exception in thread "Timer-2" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-2
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.Node$7.invalidated(Unknown Source)
at javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.BooleanPropertyBase.set(Unknown Source)
at javafx.css.StyleableBooleanProperty.set(Unknown Source)
at javafx.scene.Node.setVisible(Unknown Source)
at Pantallas.PersonalContabilidad$1.run(PersonalContabilidad.java:221)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)

correct是一个标签,我显示3秒,它在correct.setVisible(false);失败,这是第221行

    correct.setVisible(true);
    timer.schedule(new TimerTask() {
    @Override
        public void run() {
        correct.setVisible(false);
    }
    }, 3*1000);

2 个答案:

答案 0 :(得分:10)

标签正确应从FX应用程序线程更新。你应该在这里使用Platform.runLater()

correct.setVisible(true);
timer.schedule(new TimerTask() {
@Override
    public void run() {
    Platform.runLater(new Runnable() {
       public void run() {
          correct.setVisible(false);
      }
    });
}
}, 3*1000);

答案 1 :(得分:0)

您将收到此异常,因为您不是从FX应用程序线程调用Java FX GUI元素。您只需从GUI线程访问GUI元素即可。您可以使用runLater(Runnable)来确保您的代码在正确的线程中执行。