Issue
I'm developing an application where I need to show a splash screen for 3 seconds. The problem is that the splash window is blank for three seconds and the splash image is shown only after the main stage has appeared on screen.
Here is my code:
class Launcher extends Application {
@Override
public void start(Stage stage) {
Pane splashLayout = new VBox();
ImageView splashImage = new ImageView(new Image(getClass().getResourceAsStream("splash/splash.png")));
splashLayout.getChildren().add(splashImage);
Scene scene = new Scene(splashLayout, Color.TRANSPARENT);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
Thread.sleep(3000); // wait for three seconds.
Window window = new Window(); // main stage
window.show();
stage.hide();
}
}
Now the problem here is the splash image is shown after the Window stage is shown.
Solution
Never call sleep on the JavaFX application thread - all it will do is hang your UI (which is what is happening in your code).
Use a PauseTransition
instead.
splashStage.show();
PauseTransition pause = new PauseTransition(Duration.seconds(3_000));
pause.setOnFinished(event -> {
Stage mainStage = new Stage();
mainStage.setScene(createMainScene());
mainStage.show();
splashStage.hide();
});
pause.play();
Also, don't call new Window()
. Call new Stage()
instead - Stages are more function than Windows and there are no real reasons to forgo that functionality and use a Window.
Sometimes, you want to do some work while the splash screen is being displayed (some I/O, a computationally intensive task, load hobbits with pie, find dwarves, whatever), in that case you can use the JavaFX concurrency utilities as demonstrated in this splash screen sample.
Answered By - jewelsea
Answer Checked By - Timothy Miller (JavaFixing Admin)