Search code examples
javaswingembedded-resourceimageicon

Image is not being displayed with setIcon()


I have the following code in my program:

JLabel status = new JLabel();  
status.setBorder(BorderFactory.createLineBorder(Color.BLACK));  
status.setBounds(400, 30, 380, 200);
status.setIcon(new ImageIcon("C:........./logo2.png")); 
status.setLocation(50, 750);
add(status); 

But now I want to remove the path from setIcon(new ImageIcon("path")) to an image that I have inside a folder in my project.

I tried to do this:

status.setIcon(new ImageIcon("src/folder/logo2.png")); 

But it didn't display anything.

I find this topic and tried this too:

ImageIcon(this.getClass().getResource("src/files/logo2.png"));

But it gives me a NullPointer.

This is the structure of my project:

enter image description here

How can I display this image correctly?


Solution

  • Look you have to create a new Folder under the Project folder, call it resources or any thing you want. After that you can refer to your resources as getClass().getResource("resources/thefile.png").toFile() Hope that helps