Adding ImageIcon to JPanel not working

Aaron Esau picture Aaron Esau · Jan 1, 2015 · Viewed 9.8k times · Source

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.

Answer

MadProgrammer picture MadProgrammer · Jan 1, 2015

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