有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

为了提高UI的人机界面,我想切换spinner 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) 个答案

  1. # 1 楼答案

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

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

    对于脱离JavaFX的线程逻辑,应该使用Task,然后可以将spinner visible属性绑定到task running属性,而不是使用runLater