为什么 Thread.sleep() 在 JavaFX 中不起作用?

Zar*_*rif 0 java sleep javafx thread-sleep

当我使用 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");
}
Run Code Online (Sandbox Code Playgroud)

当按下按钮 b1 时,将调用写入函数。现在,在 2 秒后在控制台中打印“Value + i”。但是那个时候标签 l1 的文本没有改变,最后它只变成了“LAST TIME”。这里有什么问题?

c0d*_*der 5

阅读评论中建议的链接后,您可能希望从 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();
}
Run Code Online (Sandbox Code Playgroud)

或者更好地使用 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();
}
Run Code Online (Sandbox Code Playgroud)