Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constantly Update UI in Java FX worker thread

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?

like image 423
Killerpixler Avatar asked Dec 10 '13 15:12

Killerpixler


People also ask

Why is JavaFX not thread safe?

Thread safety in a JavaFX application cannot be achieved by synchronizing thread actions. We must ensure that the programs that manipulate the scene graph must do so only from the JavaFX Application Thread. Therefore, multithreading in JavaFX has to be handled in a different manner.

Does JavaFX use threads?

JavaFX uses a single-threaded rendering design, meaning only a single thread can render anything on the screen, and that is the JavaFX application thread. In fact, only the JavaFX application thread is allowed to make any changes to the JavaFX Scene Graph in general.

What is JavaFX platform runLater?

runLater(r) is a static method in class Platform, from package javafx. application. The parameter is an object of type Runnable, the same interface that is used when creating threads. Platform. runLater(r) can be called from any thread.

What is the use of JavaFX?

JavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.


1 Answers

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();
like image 77
zhujik Avatar answered Oct 19 '22 23:10

zhujik