本文介绍了Java FX使用/不使用Platform.runLater修改UI组件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java fx控制器中我有两个版本的代码,只需按一个按钮就可以在标签上设置文本(这只是一个示例,但可以考虑任何其他ui修改)......

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)...

第一个版本使用Platform.runLater:

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);

两者都工作得非常好,但我知道到目前为止只有将一些runnable传递给Platform.runLater将保持执行顺序。

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.

使用Platform.runLater还有其他任何显着差异或动机吗?

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

推荐答案

JavaFX只有一个UI线程

如果您有长时间运行的任务,您将需要运行它们后台线程和完成此类线程后,您可能希望将结果更新回th e UI。在这种情况下,您使用 Platform.runlater()包围的更新。使用Platform.runLater在您的代码周围使您的代码能够与JavaFX应用程序线程进行通信。

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.

来到您的问题:

我希望大多数它已经回答了,只是为了添加

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

1。 如果您已经在JavaFX应用程序线程

2,则不必使用Platform.runlater()。正如说

2 . As the Platform.runLater() doc says

我们不确定何时进行更新,这取决于等待处理的更新数量。如果等待在UI线程上处理许多更新,则可能需要一些时间(通常不会发生这种情况)

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)

这篇关于Java FX使用/不使用Platform.runLater修改UI组件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 21:02