2016-01-25 165 views
2
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")不执行,我的意思是文本框没有其文本设置为“START”,为什么?如何解决这个问题?Platform.runLater问题 - 延迟执行

+0

相关链接:[JavaFX的8:如何将添加纯滞后的听众(http://stackoverflow.com/questions

您可以在一个新的线程运行上面的所有代码解决这个问题/ 34784037/javafx-8-how-to-add-a-timedelay-to-a-listener)和[等待改变属性后改变JavaFX 8](http://stackoverflow.com/questions/22263008/wait- before-react-to-a-property-change-javafx-8) – jewelsea

回答

5

请记住,在JavaFX线程上调用该按钮的onAction,因此您有效地将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(); 
    }); 
+0

谢谢....它的工作! – Walker

+3

很好的解释了为什么 - 虽然注意到fx带有广泛的高级动画支持:-) @Walker – kleopatra

+2

第一个'runLater'是不必要的。由于事件处理程序在应用程序线程上运行,'field.setText(“START”)'可以安全地移动到'Runnable'的“外部”。 – fabian