为什么 Thread.sleep() 在 JavaFX 中不起作用? [英] Why Thread.sleep() doesn't work accordingly in 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屋!