Siva Subramaniam Siva Subramaniam - 2 months ago 3x
Java Question

Image not loading in jar file

I am trying to fix this problem. Trying different solutions but nothing works. I am using NetBeans IDE. I created a project with this structure and files:


The image files are in


I have specified working folder for my project in Netbeans as

I have created my image icons like this

new ImageIcon("device21.png");

In my source file, it works perfectly while running the project in Netbeans but images are not showing up when I build and run my JAR file separately. But the image files are inside the JAR.

I have also tried the answers for the same question asked previously.

URL imageUrl=getClass().getResource("device21.png");
new ImageIcon(imageUrl);

But it doesn't work in my case. I am building a JAR file for the first time. Can anyone help me with this!!


A simple way of doing this will be to add the image in your classpath or a directory in your classpath say img as shown below:


And then load your image from this location like this:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("img/device21.png");
ImageIcon icon = new ImageIcon(resource);