Platform.runLater问题 - 延迟执行 [英] Platform.runLater Issue - Delay Execution

查看:1797
本文介绍了Platform.runLater问题 - 延迟执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,为什么?如何解决此问题?

After running the code above, field.setText("START") is not executed, I mean textfield did not set its text to "START", WHY? How to resolve this?

推荐答案

请记住,在JavaFX线程上调用按钮的 onAction ,因此您实际上会停止UI线程5秒钟。当UI线程在这五秒结束时被解冻时,两个更改都会连续应用,因此您最终只能看到第二个。

Keep in mind that the button's onAction is called on the JavaFX thread, therefore you are effectively halting your UI thread for 5 seconds. When the UI thread is un-frozen at the end of these five seconds both changes are applied successively, so you end up only seeing the second.

你可以通过在新线程中运行上面的所有代码来解决这个问题:

You can fix this by running all code above in a new thread:

    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();
    });

这篇关于Platform.runLater问题 - 延迟执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆