繁体   English   中英

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

[英]Constantly Update UI in Java FX worker thread

我的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方法updateMessage不到该点。

怎么了?

您需要在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();

装饰性更改为塞巴斯蒂安的代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM