TheShield
TheShield

Reputation: 307

Image not showing up in Java Swing GUI JFrame

I have a main function that calls this function:

private void splashScreen() throws MalformedURLException {
    JWindow window = new JWindow();
    ImageIcon image = new ImageIcon(new URL("https://i.imgur.com/Wt9kOSU.png"));
    JLabel imageLabel = new JLabel(image); 
    window.add(imageLabel);
    window.pack();
    window.setVisible(true);
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    window.setVisible(false);
    window.dispose();
}

I have added the image to the window, packed the window and then made it visible, the frame pops up but, the image does not show up in the frame. I am fairly certain that this code should work?

Upvotes: 0

Views: 91

Answers (2)

Dreamspace President
Dreamspace President

Reputation: 1118

Like camickr said, a Swing Timer would be the proper way to deal with this. But since creating custom threads is something you will do a lot in the future, here's a "manual" example for how you could solve this:

private void showSplashScreen() {

    [Create window with everything and setVisible, then do this:]

    final Runnable threadCode = () -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(window::dispose); // Closes the window - but does so on the Swing thread, where it needs to happen.
        // The thread has now run all its code and will die gracefully. Forget about it, it basically never existed.
        // Btw., for the thread to be able to access the window like it does, the window variable either needs to be "final" (((That's what you should do. My mantra is, make EVERY variable (ESPECIALLY method parameters!) final, except if you need them changeable.))), or it needs to be on class level instead of method level.
    };

    final Thread winDisposerThread = new Thread(threadCode);
    winDisposerThread.setDaemon(true);  // Makes sure that if your application dies, the thread does not linger.
    winDisposerThread.setName("splash window closer timer"); // Always set a name for debugging.
    winDisposerThread.start(); // Runs the timer thread. (Don't accidentally call .run() instead!)
    // Execution of your program continues here IMMEDIATELY, while the thread has now started and is sleeping for 5 seconds.
}

Upvotes: 1

camickr
camickr

Reputation: 324197

You are using Thread.sleep() so the GUI sleeps and can't repaint itself. Read the section from the Swing tutorial on Concurrency for more information.

Don't use Thread.sleep().

Instead use a Swing Timer to schedule the event in 5 seconds. Read the section from the Swing tutorial on How to Use Timers for more information.

Upvotes: 3

Related Questions