enes enes - 1 month ago 8
Java Question

How to make Loading Scene before application window in javaFx?

I am triying to create a loading window before real application window openning. There is a progressBar in the loading scene and it is undeterminate.

Problem is that; progressbar does not work until the real window open when i execute the program.

here is my code;

this is screenshot

public class MainApp extends Application {

private Stage loadingStage = new Stage();


public static void main(String[] args) {
launch(args);
}

public void start(final Stage mainStage) throws Exception {
//loading..
loadingScreen();

//start...
appScreen(mainStage);
}


private void loadingScreen() {

loadingStage.initStyle(StageStyle.TRANSPARENT);
loadingStage.initStyle(StageStyle.UNDECORATED);
loadingStage.setScene(new LoadingWindow().getInitWindow());
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
loadingStage.setX((screenBounds.getWidth() - 600) / 2);
loadingStage.setY((screenBounds.getHeight() - 0) / 2);
loadingStage.show();
}

private void appScreen(final Stage mainStage) {

Platform.runLater(new Runnable() {
public void run() {

for (int i = 0; i < 10000000; i++) {
System.out.println("may be init is too long...");
}
//get real window
Scene root = new Scene(new Label("here is AppWindow...."));
mainStage.setScene(root);
mainStage.centerOnScreen();
mainStage.show();
loadingStage.close();
}
});
}
}

Answer

You can use preloaders. here is an example. taken from source

public class FirstPreloader extends Preloader {
    ProgressBar bar;
    Stage stage;

    private Scene createPreloaderScene() {
        bar = new ProgressBar();
        BorderPane p = new BorderPane();
        p.setCenter(bar);
        return new Scene(p, 300, 150);        
    }

    public void start(Stage stage) throws Exception {
        this.stage = stage;
        stage.setScene(createPreloaderScene());        
        stage.show();
    }

    @Override
    public void handleProgressNotification(ProgressNotification pn) {
        bar.setProgress(pn.getProgress());
    }

    @Override
    public void handleStateChangeNotification(StateChangeNotification evt) {
        if (evt.getType() == StateChangeNotification.Type.BEFORE_START) {
            stage.hide();
        }
    }    
}
Comments