为什么Thread.sleep()在JavaFX中不能相应地工作? [英] Why Thread.sleep() doesn't work accordingly in JavaFX?

查看:61
本文介绍了为什么Thread.sleep()在JavaFX中不能相应地工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用JavaFX时,睡眠功能不会相应地工作。如以下代码所示:

public class Controller {

@FXML private Label label;
@FXML private Button b1;

public void write() throws InterruptedException
{
    label.setText("FIRST TIME");
    for(int i=1;i<=5;i++)
    {
        System.out.println("Value "+i);
        label.setText("Value "+i);
        Thread.sleep(2000);
    }
    label.setText("LAST TIME");
}

当按下按钮b1时,将调用Write函数。现在,在控制台中,2秒后将打印"value+i"。但是此时标签L1的文本没有改变,最后它只改变为"Last time"。这里出了什么问题?

推荐答案

阅读注释中建议的链接后,您可能希望从FX线程中删除长进程(延迟)。
您可以通过调用另一个线程来执行此操作:

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

或更好地使用FX动画工具,如:

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

这篇关于为什么Thread.sleep()在JavaFX中不能相应地工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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