Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding ImageIcon to JPanel not working

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.

like image 524
Aaron Esau Avatar asked Apr 26 '26 09:04

Aaron Esau


2 Answers

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

like image 116
MadProgrammer Avatar answered Apr 27 '26 22:04

MadProgrammer


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).

like image 41
JoaaoVerona Avatar answered Apr 27 '26 21:04

JoaaoVerona