Thwoopster
Thwoopster

Reputation: 1

I can't get the ImageIcon to display properly

Everything works except when I push run, it doesn't show the icon for the label in the JFrame. Does anyone know how to fix that?

public class Frame extends JFrame
{
    private final int speed=5;
    JLabel label;
    ImageIcon icon;
    public void create() {
        this.setSize(240,228);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.addKeyListener(this);
        this.setLayout(null);
        icon=new ImageIcon("rocket.png");
        label=new JLabel();
        label.setBounds(0,0,100,100);
        label.setIcon(icon);
        this.add(label);
        this.setVisible(true);
    }
}

I've tried renaming the file, putting it in several different spots in the code, and even looked up a tutorial or two, but none of them helped.

Upvotes: -1

Views: 103

Answers (2)

CODERZ
CODERZ

Reputation: 21

As the comments have mentioned, use an ImageIO.read() instead of an ImageIcon as ImageIcon does not throw an exception and instead produces a 1x1 blank Image which makes it harder to find errors related to it. As for your error, the only possible thing that might not display your ImageIcon is that you've entered the wrong location. You have written "rocket.png" in your ImageIcon and not provided any location. This makes the program find the image in the same folder the code file is in. So, provide complete location of your image rather than just typing its name. So it should look like this:

icon = new ImageIcon("src\res\rocket.png");

Upvotes: 0

routerking2802
routerking2802

Reputation: 174

Change this:

icon=new ImageIcon("rocket.png");

to:

icon=new ImageIcon("src\\rocket.png");

Upvotes: -2

Related Questions