Jeremy Johnson
Jeremy Johnson

Reputation: 469

NullPointerException when using path name to load image file

Looked everywhere and still can't find a solution to this problem while using NetBeans.

When I use the following code to load a file by path:

Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();

I get a NullPointerException. I read somewhere where it suggested creating a new folder and making it a source file for the project, but that didn't help. I've tried multiple suggestions that I found on this site and others, but I'm not getting any results.

I'm starting to wonder if there is something wrong with the way that I am putting the path in, but I'm doing it exactly the way that it shows everywhere else. I've tried every combination of every example that I could find to solve this problem for the last couple of days, but nothing is working.

Upvotes: 4

Views: 2027

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

It seems like the images folder wasn't part of your classpath. In Eclipse, it's not in what they call the Build Path.

Right-click on the images folder, select Build Path and Use as Source Folder. The folder will now be added to the classpath whenever you run your application through Eclipse. If you do this, you need to change your path to

Image owl = new ImageIcon(this.getClass().getResource("/owl.gif")).getImage();

because now everything in images will be put directly on the classpath.

You could instead, make a package called images under your normal src folder and call it as

Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();

Upvotes: 3

Luis Sep
Luis Sep

Reputation: 2402

.getResource() returns null when it cannot find the resource. That's where you're getting the null.

Your problem is that the path for owl.gif is incorrect.

Upvotes: 1

Related Questions