Load fxml as background process - Javafx

后端 未结 3 1197
滥情空心
滥情空心 2021-01-16 02:41

My initial fxml(say home.fxml) has a lot of functionalities, hence it takes a lot of time to load completely. So to avoid the time gap between program start and

3条回答
  •  广开言路
    2021-01-16 03:33

    your approach using Task was already correct. you were just missing a bit more: you were just missing another Platform#invokeLater() to update the UI:

        new Thread(new Task() {
    
            @Override
            protected Object call() throws Exception {
                // Simulating long loading
                Thread.sleep(5000);
    
                FXMLLoader loader = new FXMLLoader(getClass().getResource("home.fxml"));
                Parent root = loader.load();
    
                Scene scene = new Scene(root);
    
                // Updating the UI requires another Platform.runLater()
                Platform.runLater(new Runnable() {
    
                    @Override
                    public void run() {
                        mainStage.setScene(scene);
                        mainStage.show();
                        stage.hide();
                        System.out.println("Stage showing");
                        // Get current screen of the stage
                        ObservableList screens = Screen.getScreensForRectangle(new Rectangle2D(mainStage.getX(), mainStage.getY(), mainStage.getWidth(), mainStage.getHeight()));
                        // Change stage properties
                        Rectangle2D bounds = screens.get(0).getVisualBounds();
                        mainStage.setX(bounds.getMinX());
                        mainStage.setY(bounds.getMinY());
                        mainStage.setWidth(bounds.getWidth());
                        mainStage.setHeight(bounds.getHeight());
                        System.out.println("thread complete");
                    }
                });
                return null;
            }
        }).start();
    

提交回复
热议问题