skyork
skyork

Reputation: 7381

NullPointerException when accessing image files in a .jar file

I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar:

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 images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.

Upvotes: 3

Views: 2339

Answers (2)

Lukasz
Lukasz

Reputation: 7662

Try this:

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

Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored.

Upvotes: 3

Michael Lorton
Michael Lorton

Reputation: 44376

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

Upvotes: 2

Related Questions