Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

javafx - Java FX modifying UI component state with/without using Platform.runLater

In java fx controller i have two version of the code that simply sets a text on a label when a button is pressed (this is just a sample, but any other ui modification can be considered)...

first version uses Platform.runLater :

Platform.runLater(() -> {
   status.setText("");
   statusIndicator.setVisible(false);
});

the other one simply modifies it in ordinary thread :

status.setText("");
statusIndicator.setVisible(false);

Both are working perfectly fine, only difference i know so far is that passing some runnable to Platform.runLater will keep the order of execution.

is there any other significat difference or motive to use Platform.runLater?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaFX has just a single UI thread

From Docs

The JavaFX scene graph, which represents the graphical user interface of a JavaFX application, is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread

In case you have long-running tasks, you will want to run them on background threads and after completion of such threads, you would want to update the result back to the UI. Under such scenario's, you use the updation surrounded with Platform.runlater(). Surrounding your code with Platform.runLater enables your code to communicate with the JavaFX Application thread.

Coming to your question :

is there any other significat difference or motive to use Platform.runLater?

I hope most of it is already answered, just to add

1 . You don't have to use Platform.runlater(), if you are already on the JavaFX Application thread

2 . As the Platform.runLater() doc says

Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future

We are not sure when the update will take place, it depends on the number of updates waiting to be processed. If a number of updates are waiting to be processed on the UI thread, it can take some time (such scenario normally doesn't happen)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...