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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With