Button button = new Button("Show Text");
button.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
Platform.runLater(new Runnable(){
@Override
public void run() {
field.setText("START");
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Platform.runLater(new Runnable(){
@Override
public void run() {
field.setText("END");
}
});
}
});
运行上面的代码后,field.setText("START")
没有被执行,我的意思是 textfield 没有将它的文本设置为“START”,为什么?如何解决?
最佳答案
请记住,按钮的 onAction
是在 JavaFX 线程上调用的,因此您实际上是将 UI 线程暂停了 5 秒。当 UI 线程在这五秒结束时解冻时,两个更改都会相继应用,因此您最终只会看到第二个。
您可以通过在新线程中运行上面的所有代码来解决此问题:
Button button = new Button();
button.setOnAction(event -> {
Thread t = new Thread(() -> {
Platform.runLater(() -> field.setText("START"));
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Platform.runLater(() -> field.setText("END"));
});
t.start();
});
关于java - Platform.runLater 问题 - 延迟执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34985943/