首页 > 解决方案 > 如何在不冻结 UI 的情况下休眠代码?

问题描述

所以,我正在开发一个 javafx 应用程序,我正在尝试在场景 1 和场景 2 之间切换,但两者中间都有一个“加载”场景。我试图Thread.sleep()在切换到场景 2 之前模拟加载屏幕动画,但是动画冻结(是的,我知道这是因为那个线程是“UI 线程”)。

我已经尝试过使用时间表但不起作用,我很新,我可能做错了什么哈哈

我能做些什么?寻找简单的东西。

我的代码:

private void handleButton(ActionEvent event) throws Exception {
        if(true){
            Node node=(Node) event.getSource();
            Stage stage=(Stage) node.getScene().getWindow();
            Parent root= FXMLLoader.load(getClass().getResource("LoadingFXML.fxml"));
            Scene loading= new Scene(root);
            stage.setScene(loading);
            stage.show();
            
            Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
            
               public void handle(ActionEvent event) {
                  System.out.println("Waiting");
                }
            }));
            timeline.setCycleCount(1);
            timeline.play();

            root=FXMLLoader.load(getClass().getResource("Scene2FXML.fxml"));
            Scene scene2=new Scene(root);
            stage.setScene(scene2);
            stage.show();
           
        }
    }

固定的:

private void handleButton(ActionEvent event) throws Exception {
        if(true){
            Node node=(Node) event.getSource();
            Stage stage=(Stage) node.getScene().getWindow();
            Parent root= FXMLLoader.load(getClass().getResource("LoadingFXML.fxml"));
            Scene loading= new Scene(root);
            stage.setScene(loading);
            stage.show();
            root=FXMLLoader.load(getClass().getResource("Scene2FXML.fxml"));
            Scene scene2=new Scene(root);
            
            Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
            
               public void handle(ActionEvent event) {
                  stage.setScene(scene2);
                  stage.show();;
                }
            }));
            timeline.setCycleCount(1);
            timeline.play();

            
            
           
        }
    }

标签: javajavafx

解决方案


您的handleButton()方法在主线程中运行,用于 UI 界面绘制和对用户操作作出反应。

在不同的线程中运行此方法内容。在这种情况下,如果你调用sleep(),它不会冻结 UI 界面。


推荐阅读