How to create splash screen as a Preloader in JavaFX standalone application?

前端 未结 3 676
说谎
说谎 2021-01-11 17:33

I created a Preloader (based on the following tutorial) that should display a splash screen for the main application.

9.3.4 Using a Preloader to Display the Applicat

3条回答
  •  太阳男子
    2021-01-11 17:59

    May be too late, this can also help somebody. For me, i used JavaFX service and task to create splash screen as a Preloader in JavaFX standalone application. This, because the contexte of my project.

    Create the AnchorPane and the progress Pane

    @FXML
    private AnchorPane anchorPane;
    private MaskerPane progressPane;
    
    
    public static void main(String[] args) {
        launch(args);
    }
    
        @Override
    public void init() throws Exception {
        progressPane = new MaskerPane();
        progressPane.setText(bundle.getString("root.pleaseWait"));
        progressPane.setVisible(false);
        AnchorPane.setLeftAnchor(progressPane, 0.0);
        AnchorPane.setTopAnchor(progressPane, 0.0);
        AnchorPane.setRightAnchor(progressPane, 0.0);
        AnchorPane.setBottomAnchor(progressPane, 0.0);
        anchorPane.getChildren().add(progressPane);
    }
    
    @Override
    public void start(Stage initStage) {
      //.....
        initRoot();
     //.....
    
    }
    

    Create the splash screen service as this:

    private final Service splashService = new Service() {
        @Override
        protected Task createTask() {
            return new Task() {
                @Override
                public Void call() throws Exception {
                    //main code, the code who take time
                    //or
                    //Thread.sleep(10000);
                    return null;
                }
            };
        }
    };
    

    Start service and show/hide the progressPane on initRoot when loading the main screen:

       public void initRoot() {
        try {
            //....
    
            splashService.restart();
            //On succeeded, do this
            splashService.setOnRunning(new EventHandler() {
                @Override
                public void handle(WorkerStateEvent event) {
                    //Show mask on succeed
                    showMask(Boolean.TRUE);
                }
            });
            splashService.setOnSucceeded(new EventHandler() {
                @Override
                public void handle(WorkerStateEvent event) {
                    splashService.cancel();
                     //Hide mask on succeed
                    showMask(Boolean.FALSE);
                }
                });    
                //.....
                primaryStage.show();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    

    To show/hide the progress...

    showMask(boolean value){
            progressPane.setVisible(value);
    };
    

提交回复
热议问题