在Java FX工作线程中不断更新UI

时间:2013-12-10 15:02:59

标签: java multithreading javafx-2 task

我的FXML应用程序中有Label label

我希望这个标签每秒更换一次。目前我用这个:

        Task task = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            int i = 0;
            while (true) {
                lbl_tokenValid.setText(""+i);
                i++;
                Thread.sleep(1000);
            }
        }
    };
    Thread th = new Thread(task);
    th.setDaemon(true);
    th.start();

但是没有发生任何事情。

我没有任何错误或例外。 我不需要在主GUI线程中更改标签的值,因此我没有在updateMessageupdateProgress方法中看到这一点。

有什么问题?

2 个答案:

答案 0 :(得分:37)

您需要在JavaFX UI线程上更改场景图。 像这样:

Task task = new Task<Void>() {
  @Override
  public Void call() throws Exception {
    int i = 0;
    while (true) {
      final int finalI = i;
      Platform.runLater(new Runnable() {
        @Override
        public void run() {
          label.setText("" + finalI);
        }
      });
      i++;
      Thread.sleep(1000);
    }
  }
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();

答案 1 :(得分:14)

塞巴斯蒂安代码的化妆品改变。

 while (true)
 {
   final int finalI = i++;
   Platform.runLater ( () -> label.setText ("" + finalI));
   Thread.sleep (1000);
 }