NullPointerException on accessing image files in a .jar file

I tried almost everything, but still have this problem. I have the following setup: I have an images.jar file containing a folder called "images" in which there are several image files. I add images.jar to the java build path of the project in eclipse, and I tried to use the following code to access individual images in the bank:

URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);

Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put the image.jar file, as it is added to the classpath in eclipse. I also tried using the path "/images/a.png", but still the same question. Any suggestion would be very welcome! Thank.

+3
source share
3 answers

Try the following:

URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);

Without a call, getClassLoader()you can access the resources in the JAR file where the code is stored.

+3
source

I could not reproduce your problem, but my theory is that you are using the class from a different place than you think - that the image and the class are in different jars or the class is read directly from the class file.

+2
source

The related images section in this link may be useful: http://leepoint.net/notes-java/GUI-lowlevel/graphics/45imageicon.html

0
source

Source: https://habr.com/ru/post/1782041/


All Articles