0

I am trying to run two threads for my JavaFX program. The first thread (We'll call thread 1) is built to collect sensor input from a rangefinder sensor and a camera. Thread 1 updates a variable within the StageWithData (a class that inherits Stage). That variable is then tied to a label in my second GUI thread. The connection is formed using the "bind" method. However, whenever the sensor updates, Java gives me an error

"Thread-4 javalang.IllegalStateExpression: Not on FX application thread; currentThread = Thread-4"

I understand why the error occurs, just do not know how to fix it.

Any advice? I am pretty new to threading.

Thanks!

ZooHe17
  • 23
  • 8
  • https://stackoverflow.com/questions/21083945/how-to-avoid-not-on-fx-application-thread-currentthread-javafx-application-th?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – JKostikiadis Jun 14 '18 at 20:19

2 Answers2

0

You have to wrap the update call for your variable in a Platform.runLater call because such an update must happen on the JavaFX application thread and on no other thread.

mipa
  • 10,369
  • 2
  • 16
  • 35
0

JavaFX applications all contain at least one thread, called the "JavaFX Application Thread" (JFXAT). This thread is the only one that can handle changes to visual elements of your application.

When you create a background thread, the JFXAT is not accessible from the new thread.

The only way a background thread can interact with the JFXAT is by wrapping the UI updates within a Platform.runLater() call (with only a handful of specialized exceptions).

In your background thread, this is accomplished quite simply with the following Lamba expression:

Platform.runLater(() -> {
    // Code to update the UI goes here
});

This essentially sends that block of code to the JFXAT where it is executed properly.

Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • do you know how to stop a thread that is running a task? The task finished its "Call" method, but the process seems to still be running. @Zephyr – ZooHe17 Jun 14 '18 at 21:17
  • You'll want to search for that or post it as a separate question (but search first) :) – Zephyr Jun 14 '18 at 21:28
  • Nevermind I figure it out. I had Platform.setImplicitExit() to true for some reason. Thanks again – ZooHe17 Jun 14 '18 at 21:31