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

Kil*_*ler 18 java multithreading task javafx-2

我有Label label我的FXML应用程序.

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

        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();
Run Code Online (Sandbox Code Playgroud)

然而,什么也没发生.

我没有得到任何错误或例外.我不需要在主GUI线程中更改标签的值,所以我没有看到updateMessage或者updateProgress方法中的点.

怎么了?

Seb*_*ian 36

您需要在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();
Run Code Online (Sandbox Code Playgroud)


dmo*_*ony 14

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

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