How to properly execute Thread.sleep() in javaFX? [duplicate]

六眼飞鱼酱① 提交于 2021-02-07 20:02:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!