JavaFx-Thread.sleep(1000)之前的代码不起作用,为什么? [英] JavaFx - Code before Thread.sleep(1000) doesn't work, why?

查看:62
本文介绍了JavaFx-Thread.sleep(1000)之前的代码不起作用,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码段可能是什么问题?

What could be the problem with the snippet below?

    @FXML 
    private Button btnLogOut;
    @FXML
    private Label lblStatus;

    @FXML 
    private void btnLogOut_Click() throws InterruptedException {
        lblStatus.setText("Logging out.."); // Doesn't work..?
        Thread.sleep(1000);
        System.exit(0);
    }

预先感谢您的帮助.

推荐答案

在应用程序线程上使用Thread.sleep可以防止UI更新.为防止这种情况,您需要在其他线程上运行代码以等待/关闭,并允许应用程序线程继续执行其工作:

By using Thread.sleep on the application thread you prevent the UI from updating. To prevent this you need to run the code for waiting/shutting down on a different thread and allow the application thread to continue doing it's job:

@FXML 
private void btnLogOut_Click() {
    // update ui
    lblStatus.setText("Logging out..");

    // delay & exit on other thread
    new Thread(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        System.exit(0);
    }).start();
}

您可能要考虑使用 Platform.exit() 而不是System.exit.

这篇关于JavaFx-Thread.sleep(1000)之前的代码不起作用,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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