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

查看:30
本文介绍了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?

推荐答案

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

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天全站免登陆