问题
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 ?
回答1:
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();
来源:https://stackoverflow.com/questions/49881109/how-to-properly-execute-thread-sleep-in-javafx