我正在实现一个菜单操作,需要在操作的开头和结尾更新Text组件。
这是我的代码示例:
MenuItem menuItem = new MenuItem("My Action", new ImageView("path/to/my/icon"));
menuItem .setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
infoTxt.setText("Beginning");
try {
System.out.println("sleeping...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("resuming...");
infoTxt.setText("Ending");
}
});
infoTxt
的文字仅在行动结束时更新&#34;结尾&#34;值。
是否可以显示&#34;开始&#34;到达行动结束前的价值?
答案 0 :(得分:1)
我认为您的Thread.sleep()
会阻止初始setText()
。睡觉后第二次覆盖它。在单独的线程中移动需要时间的代码。但请务必使用setText()
在ui线程上执行第二个runLater()
。请试试这个:
infoTxt.setText("Beginning");
new Thread(() -> {
try {
System.out.println("sleeping...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("resuming...");
Platform.runLater(() -> {
infoTxt.setText("Ending");
});
}
}).start();