Search code examples
javaswingjpanelcardlayout

Is there a way to know if a JPanel is finished loading it's content?


I'm writing an application that adds cards (JPanels) to a CardLayout during runtime. The problem is that some components on the card loads faster than others, making it appear glitchy and not properly rendered before it's displayed.

I want it to be ready when shown for the first time.

I have solved the issue temporary by a loading screen, which makes the thread sleep for 1500 ms. Is there a more exakt way to know if everything on the panel is loaded?

private void showLoadingScreen() {
    final Component glassPane = getGlassPane();
    setGlassPane(loadingPanel);
    loadingPanel.setVisible(true);

    Thread thread = new Thread() {
        public void run() {
            try {;
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            setGlassPane(glassPane);
        }
    };

    thread.start();
}

Solution

  • Do all your file loading and data manipulation in a background thread that is created using a SwingWorker. Then before executing the SwingWorker, add a PropertyChangeListener. When the PropertyChangeEvents newValue is SwingWorker.StateValue.DONE, then you know all background work is done and you can display your GUI.

    Please have a look at the Concurrency in Swing tutorial, and for an example, please have a look at this answer to a similar question.