Search code examples
javaswingjframesplash-screen

Execute code only when JFrame is visible on screen executes earlier


I have a JFrame called splash_window that I am using as a splash screen for my app and it displays first. It has a progress bar which is at 0% at first and I want it to change to 5% and execute some other commands as soon as it becomes visible to the user.
When I run the app the app, the progress bar's progress is already at 5% before my splash screen becomes visible and I can see in the console that my other commands are being executed.
My question is this: How can I make it so that the commands will be executed as soon as the splash screen becomes visible to the user on screen?

My code:

//making the splash_window visible after adding all components to it
splash_window.setVisible(true);

//Used to detect when the splash_window is visible to the user
if (splash_window.isShowing()){

    //Used to know if the splash_window is visible
    System.out.print("Splash screen is complete and now visible." + System.lineSeparator());

    //Method used to increase my progress by 5%
    initProgress.setValue(getProgress(5));

    //Other commands...
}

Solution

  • You can add a window listener to the frame and update the progress when the window is opened. Here is an example:

    splash_window.addWindowListener(new WindowListener() {
    
            @Override
            public void windowOpened(WindowEvent e) {
                initProgress.setValue(getProgress(5));
                initProgress.revalidate();
            }
    
            ...
    
        });