【问题标题】:Platform.runLater Issue - Delay ExecutionPlatform.runLater 问题 - 延迟执行
【发布时间】:2016-05-01 08:51:57
【问题描述】:
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”,WHY?如何解决?

【问题讨论】:

标签: java javafx javafx-2 javafx-8


【解决方案1】:

请记住,按钮的 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();
    });

【讨论】:

  • 很好地解释了原因 - 尽管请注意 fx 带有对动画的广泛高级支持 :-) @Walker
  • 第一个runLater是不必要的。由于事件处理程序在应用程序线程上运行,field.setText("START") 可以安全地移动到Runnable 的“外部”。
猜你喜欢
  • 1970-01-01
  • 2011-01-25
  • 2018-02-25
  • 2011-09-23
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多