Adding ImageIcon to JPanel not working

11,223

Solution 1

ImageIcon(String) assumes that the specified String value is a file on the file system

Based on you description I would guess that the image is embedded within the application, meaning that it is not longer accessible as a File, but instead needs to accessed as a URL or InputStream

Because the image and class are in the same package you can use something like

ImageIcon img = new ImageIcon(getClass().getResource("image.png"));

Assuming you're loading it from MainClass

Solution 2

You must specify the full path, seeing it from the root of your application.

In your case, you must use new ImageIcon("com/package/image.png", null).

Solution 3

EDIT

I looked at some old code with a similar situation turns out I added the image to a JLabel first and then to the JPanel.

Try adding the Image to a JLabel and then add that JLabel to the JPanel as follows.

ImageIcon image = new ImageIcon(this.getClass().getResource("image.png"));
JLabel picLabel = new JLabel(image);
panel.add(picLabel);
Share:
11,223
Aaron Esau
Author by

Aaron Esau

sup

Updated on June 28, 2022

Comments

  • Aaron Esau
    Aaron Esau over 1 year

    I am trying to add an ImageIcon to my JPanel.

    ImageIcon image = new ImageIcon("image.png", null);
    JLabel label = new JLabel(image, JLabel.CENTER);
    panel.add(label);
    

    Ok. The image is is located in the same folder as the class...

    com.package
              |- mainclass.java
              |- image.png
              V
    

    For whatever reason, the imageicon will not display in the JPanel. I try/catch-ed it, but no use. No errors at all!

    I am on Windows.