JavaFX:从Thread更新Controller类中的UI元素 [英] JavaFX: Updating UI elements in a Controller class from a Thread

查看:121
本文介绍了JavaFX:从Thread更新Controller类中的UI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaFX中,我有一个Controller类,它从FXML文件中提取控制组件,并具有作用于组件的方法,在这里用标签显示:

In JavaFX, I have a Controller class that pulls control components from an FXML file and has methods that act on the component, shown with a Label here:

public class ViewController {
    @FXML private Label labelStatus;

    public void updateStatusLabel(String label) {
        labelStatus.setText("Status: " + label);
    }    
}

我还有一个带有run()的Java线程方法,如下所示:

I also have a Java Thread with a run() method, like this:

public class Server extends Thread {

    public void run() {
        super.run();    
    }
}

此服务器线程处理我需要的一些套接字连接我的特定申请。建立连接后(在run()方法中 - 未显示),我需要更新FXML控制器中的Label。我该怎么办?

This Server thread handles some socket connections that I need for my particular application. After a connection has been established (in the run() method -- not shown), I need to update the Label in the FXML Controller. How would I do this?

注意:我故意使我的代码和问题一般,所以它可以帮助其他人解决同样的问题。

Note: I've purposely made my code and question general so it may help others with the same problem.

推荐答案

你打电话给 Platform.runLater(runnable),以执行可在JavaFX UI线程上更新活动JavaFX场景图元素的runnable。

You call Platform.runLater(runnable) off the JavaFX UI thread to execute a runnable that updates elements of the active JavaFX Scene Graph on the JavaFX UI thread.

同时查看 JavaFX中的并发,使用任务服务类,看看这是不是更合适的解决方案你的特殊任务。

Also review Concurrency in JavaFX, with the Task and Service classes and see if that is not a more appropriate solution to your particular task.

有关更多信息,请参阅:

For more information, see:

  • Usage of JavaFX Platform.runLater and access to UI from a different thread.
  • Platform.runLater and Task in JavaFX
  • JavaFx response to SwingUtilities.invokeLater

这篇关于JavaFX:从Thread更新Controller类中的UI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆