官术网_书友最值得收藏!

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();
主站蜘蛛池模板: 锦屏县| 济源市| 庄河市| 富顺县| 金沙县| 叶城县| 新源县| 安化县| 武夷山市| 合山市| 黔江区| 延津县| 华亭县| 郯城县| 阳高县| 阳西县| 汤原县| 延庆县| 和林格尔县| 台安县| 襄樊市| 两当县| 时尚| 莱西市| 察哈| 永嘉县| 逊克县| 宜春市| SHOW| 颍上县| 兴业县| 义马市| 宜良县| 邹城市| 万山特区| 特克斯县| 丰宁| 营山县| 内江市| 巫山县| 武城县|