4

I am writing a simple code that displays the content of a table with javaFX. I would like the program to pause every time a new content is displayed.

for(int i = 0; i < table.size(); i++){
    label.setText(table[i]);
    Thread.sleep(2000); // The program stops for 2 seconds 
}

The problem is, Thread.sleep() doesn't work as planed. In fact, the program pauses before even displaying the content.

How can I correct this issue ?

Toms River
  • 196
  • 1
  • 4
  • 13
  • 1
    Don't use it. Use `Timeline`. https://stackoverflow.com/questions/9966136/javafx-periodic-background-task – SedJ601 Apr 17 '18 at 14:45

1 Answers1

4

You should use a Timeline for this task. It allows you to trigger events running on the application thread repeatedly in a given interval without preventing the layout/rendering of the scene by blocking the JavaFX application thread.

label.setText(table[0]); // set text for the first time

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(2), new EventHandler<ActionEvent>() {

    private int i = 1;    

    @Override
    public void handle(ActionEvent event) {
        label.setText(table[i]); // display next string
        i++;
    }
}));
timeline.setCycleCount(table.length - 1);
timeline.play();
fabian
  • 80,457
  • 12
  • 86
  • 114