Why Thread.sleep() doesn't work accordingly in JavaFX?
After having read the links proposed in the comments, you may want to remove the long process (delay) from the fx thread.
You can do it by invoking another thread :
public void write() {
label.setText("FIRST TIME");
new Thread(()->{ //use another thread so long process does not block gui
for(int i=1;i<=6;i++) {
String text;
if(i == 6 ){
text = "LAST TIME";
}else{
final int j = i;
text = "Value "+j;
}
//update gui using fx thread
Platform.runLater(() -> label.setText(text));
try {Thread.sleep(2000);} catch (InterruptedException ex) { ex.printStackTrace();}
}
}).start();
}
Or better use fx animation tools like :
private int i = 0; // a filed used for counting
public void write() {
label.setText("FIRST TIME");
PauseTransition pause = new PauseTransition(Duration.seconds(2));
pause.setOnFinished(event ->{
label.setText("Value "+i++);
if (i<=6) {
pause.play();
} else {
label.setText("LAST TIME");
}
});
pause.play();
}
I would try to create new thread used for time delay.
package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class Controller implements Runnable{
private volatile boolean isRunning = false;
private Thread timer;
private int delay = 2000;
@FXML
private Label label;
@FXML
private Button button;
private void start(){
timer = new Thread(this, "timer");
isRunning = true;
timer.start();
}
private void stop(){
isRunning = false;
}
private void interrupt(){
isRunning = false;
timer.interrupt();
}
@Override
public void run() {
int counter = 0;
while (isRunning) {
try {
++counter;
String text = "MyText" + counter;
Platform.runLater(() -> label.setText(text));
if (counter == 5) {
stop();
}
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
It is essential to update the label under Platform.runLater()
- the JavaFx main thread is the only thread permitted to update JavaFx objects.