Mastering JavaFX 10
上QQ阅读APP看书,第一时间看更新

Working with JavaFX Application Thread

Despite the development of the technology, building a thread-safe UI toolkit is still an enormous challenge due to the complexity of the events and state handling. JavaFX developers decided to follow Swing pattern, and instead of fighting endless deadlocks proclaimed that everything in the UI should be updated from and only from a special thread. It's called JavaFX Application Thread.

For simple programs, you don't notice this requirement, as common JavaFX program entry points are already run on this thread.

Once you started adding multithreading to your application, you will need to take care of the thread you use to update the UI. For example, it's a common approach to run a lengthy operation on the separate thread:

new Thread(() -> {
//read myData from file
root.getChildren().add(new Text(myData));
}).start();

This code tries to access JavaFX UI from a common Thread, and it will lead to:

java.lang.IllegalStateException: Not on FX application thread

To address that, you need to wrap your JavaFX code in the next construction:

Platform.runLater(()-> {
root.getChildren().add(new Text("new data"));
});

Note that you can not construct UI objects on JavaFX Application Thread. But, once you have showed them to the user you need to follow the JavaFX UI Thread rule.

Also, note that having one thread for the update UI means that while you run your code on this thread nothing is being updated, and the application looks frozen for the user. So, any long computational, network, or file-handling tasks should be run on a regular thread.

If you need to check in your code which thread you are on, you can use the following API:

boolean Platform.isFxApplicationThread();