Why Thread.sleep() doesnamp;#39;t work accordingly in JavaFX?(为什么Thread.sleep()在JavaFX中不能相应地工作?)
本文介绍了为什么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中不能相应地工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:为什么Thread.sleep()在JavaFX中不能相应地工作?
基础教程推荐
猜你喜欢
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
