Timer error java.lang.IllegalStateException

2019-04-07 07:14发布

问题:

I'm trying to show a label to say that all is correct only for 3 seconds in JRE 8 because I can't use DatePicker in JRE 7 and I recive this error.

    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 is a label and I show that 3 seconds and it fails at correct.setVisible(false); this is line 221

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

回答1:

The label correct should be updated from FX application thread. You should use Platform.runLater() here.

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


回答2:

You are getting this exception because you call a Java FX GUI element not from the FX application thread. You can access GUI elements just from the GUI Thread. You could use runLater(Runnable) to make sure that your code is executed within the right thread.