[java] JLabel Image

Started by
2 comments, last by darkpegasus 15 years, 9 months ago
I'm having troubles getting my image to show up on screen. I've triple checked and (AFAIK) it is in the right directory. I'm not very experienced with content panes, so I feel that is the problem. Any help is appreciated:
import java.awt.*;
import javax.swing.*;
 
public final class Game {

    public static void createHero(Container content) {
        JLabel heroImage = new JLabel(new ImageIcon("hero.jpeg"));
        content.add(heroImage);
    }
    
    public static void main(final String[] args) {
        // MAIN WINDOW ++
        JFrame mainWindow = new JFrame("Game Window");
        mainWindow.setSize(1020,764);
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
        Container content = mainWindow.getContentPane();
        content.setBackground(Color.white);
        mainWindow.setVisible(true);
        // MAIN WINDOW --
        createHero(content);
    }
}


Advertisement
Don't make your window visible until all your components have been added.
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][LWJGL Tutorials for NeHe][LWJGL Wiki][jMonkey Engine]
Thanks, but there was no change when I edited.
I've actually never used a "content" container before for something like this, but there are a few things that may be tripping this up.

First, I would try hard-coding the image path for now to make sure that it is actually pulling in the image ("C:\\hero.jpg") for example.

Second, I always have problems with layout managers. Try creating a JPanel first and adding the JLabel to that, then adding the JPanel to getContentPane().

Third, maybe you're only changing the local Container in createHero? Try returning it in your method and adding it to the contentPane instead.
Check out my current project on Kickstarter: Genegrafter

This topic is closed to new replies.

Advertisement