Java.lang.IllegalStateException: not for FX application thread; currentThread = Thread-4

I am trying to set the string of a Text object from a stream, but this gives me this error:

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) 

Handler Class:

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

I follow the tutorial . The guy in the tutorial does not use JavaFX.

I tried using Platform.runLater() , it works, but it crashes my program. I also tried to create a timer using the Platform.runLater(new Runnable() { }) method, but it gives me the same error as before.

+7
java multithreading javafx
source share
1 answer

Wrap timer.setText() in Platform.runLater() . Outside of this, inside the while loop add Thread.sleep(1000);

The reason for the Illegal State Exception is because you are trying to update the interface in some thread other than the JavaFX application thread.

The reason your application crashed when you added it was to overload the user interface thread, adding a process that will run in the user interface thread is infinite. Creating a sleep flow of 1000 ms will help you solve this problem.

If possible, replace while (true) with a timer or timer.

For more options, follow this link.

+15
source share

All Articles