private void showSplash( final Stage initStage, Task<?> task, InitCompletionHandler initCompletionHandler) { progressText.textProperty().bind(task.messageProperty()); loadProgress.progressProperty().bind(task.progressProperty()); task.stateProperty() .addListener( (observableValue, oldState, newState) -> { if (newState == Worker.State.SUCCEEDED) { loadProgress.progressProperty().unbind(); loadProgress.setProgress(1); initStage.toFront(); FadeTransition fadeSplash = new FadeTransition(Duration.seconds(1.2), splashLayout); fadeSplash.setFromValue(1.0); fadeSplash.setToValue(0.0); fadeSplash.setOnFinished(actionEvent -> initStage.hide()); fadeSplash.play(); initCompletionHandler.complete(); } // todo add code to gracefully handle other task states. }); Scene splashScene = new Scene(splashLayout); initStage.initStyle(StageStyle.UNDECORATED); final Rectangle2D bounds = Screen.getPrimary().getBounds(); initStage.setScene(splashScene); initStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2); initStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2); initStage.show(); }
@Override public void start(Stage primaryStage) throws Exception { // creating Layout final Group root = new Group(); Scene scene = new Scene(root, 400, 400); primaryStage.setScene(scene); primaryStage.setResizable(false); StackPane waitingPane = new StackPane(); final ProgressBar progress = new ProgressBar(); Label load = new Label("loading things..."); progress.setTranslateY(-25); load.setTranslateY(25); waitingPane.getChildren().addAll(new Rectangle(400, 400, Color.WHITE), load, progress); root.getChildren().add(waitingPane); // Task for computing the Panels: Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { for (int i = 0; i < 20; i++) { try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException ex) { ex.printStackTrace(); } final double prog = i * 0.05; Platform.runLater( new Runnable() { public void run() { progress.setProgress(prog); } }); } return null; } }; // stateProperty for Task: task.stateProperty() .addListener( new ChangeListener<Worker.State>() { @Override public void changed( ObservableValue<? extends State> observable, State oldValue, Worker.State newState) { if (newState == Worker.State.SUCCEEDED) { loadPanels(root); } } }); // start Task new Thread(task).start(); primaryStage.show(); }