为什么Thread.sleep()在JavaFX中无法正常工作? [英] Why Thread.sleep() doesn't work accordingly in JavaFX?

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

问题描述

当我使用JavaFX时,睡眠功能将无法正常工作.像下面的代码:

When i am using JavaFX, the sleep function won't work accordingly. Like in this code:

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时,将调用写入功能.现在,在控制台上2秒钟后将打印"Value + i".但是那个时候标签l1的文本没有改变,最后只变成了"LAST TIME".这里有什么问题?

when the Button b1 is pressed the write function is called. Now, in the console "Value + i" is being printed after 2 seconds. But that time the text of Label l1 doesn't change and finally it only changes to "LAST TIME". What is wrong in here ?

推荐答案

阅读注释中建议的链接后,您可能希望从fx线程中删除较长的过程(延迟).
您可以通过调用另一个线程来做到这一点:

After having read the links proposed in the comments, you may want to remove the long process (delay) from the fx thread.
You can do it by invoking another thread :

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动画工具,例如:

Or better use fx animation tools like :

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天全站免登陆