Constantly Update UI in Java FX worker thread

帅比萌擦擦* 提交于 2019-12-17 03:42:08

问题


I have Label label in my FXML Application.

I want this label to change once a second. Currently I use this:

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

However nothing is happening.

I don't get any errors or exceptions. I don't need the value I change the label to in my main GUI thread so I don't see the point in the updateMessage or updateProgress methods.

What is wrong?


回答1:


you need to make changes to the scene graph on the JavaFX UI thread. like this:

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



回答2:


Cosmetic change to Sebastian's code.

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


来源:https://stackoverflow.com/questions/20497845/constantly-update-ui-in-java-fx-worker-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!