如何在javaFX中正确执行Thread.sleep()? [英] How to properly execute Thread.sleep() in javaFX?

查看:364
本文介绍了如何在javaFX中正确执行Thread.sleep()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的代码,用javaFX显示表的内容. 我希望该程序在每次显示新内容时都暂停.

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 
}

问题是,Thread.sleep()无法按计划工作.实际上,该程序在显示内容之前就暂停了.

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

如何解决此问题?

推荐答案

对于此任务,您应该使用Timeline.它允许您以给定的时间间隔重复触发在应用程序线程上运行的事件,而不会通过阻塞JavaFX应用程序线程来防止场景的布局/渲染.

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();

这篇关于如何在javaFX中正确执行Thread.sleep()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆