如何在可运行的Runnable中隐藏JavaFX组件?

时间:2014-04-04 14:42:44

标签: java concurrency runnable

我试图解决并发问题。当我单击按钮登录我的系统时,我会检查用户是否具有正确的登录权限,如果他们填写了我的数据模型并且用户被转发到“仪表板”。

为了改善我的UI的HCI,我想切换我的微调器UI元素的显示和隐藏,这样用户就不会认为系统已经冻结而后台任务正在运行。

我目前正在Runnable上处理此登录脚本:

        loginBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {

            // Try to verify the user with the provided credentials
            // run this on a new thread as it takes 5-10 seconds to compute
            new Thread(new Runnable() {
                @Override
                public void run() {

                    // Set the credentials to pass
                    String username = txtUsername.getText();
                    String password = txtPassword.getText();

                    if(verifyUser(username, password)){

                        // Set the loggedIn variable to true (singleton db connection)
                        ScreensFramework.connected = true;

                        // Check we build the system successfully (returns boolean)
                        if(ScreensFramework.authenticated()){
                            hideSpinner();
                            goToDashboard(new ActionEvent());
                        }
                    } else {
                        // there was an error with the connection
                        hideSpinner();
                        setError(error);
                    }
                }
            }).start();
        }
    });

hideSpinner()方法很简单:

    private void hideSpinner(){
       spinnerWrap.setVisible(false);
    }

我遇到的问题是,我无法在我的runnable中调用hideSpinner(),为什么会这样?如何在线程运行时让组件更新。

提前致谢, 亚历克斯。

1 个答案:

答案 0 :(得分:2)

对于当前的设置,请使用runLater在JavaFX应用程序线程上操作UI。

Platform.runLater(()->spinnerWrap.setVisible(false));

您应该使用Task作为您的off JavaFX线程逻辑,然后,您可以将spinner visible属性绑定到任务运行属性,而不是使用runLater。