Reputation: 57
I'm making a Chess Game, and I've got it up an running pretty well, but I want to be able to export it as a JAR file for ease of use. but when I export it the Icons of the chesspieces that I put on the JButtons aren't there. My images are stored in a seperate folder calles Images in the same level as the src and JRE System Library. ive tried using the getClass().getResource(string)
method but it gives me a null pointer exception. ive tried the answers in articles asking similar questions such as this. but to no avail
Upvotes: 0
Views: 1833
Reputation: 417472
Most likely you pass an incorrect resource name, and since the class loader can't find it, getResource()
will return null
.
Class.getResource(String name)
expects a resource name relative to the location the class is loaded from. So if your resource is called image.jpg
, then image.jpg
must be in the same folder where the class is whose getResource()
method you're calling.
You can also specify an absolute folder inside the jar if you start it with the /
character:
getClass().getResource("/resources/images/image.jpg");
In this case the image.jpg
must be in the /resources/images
folder inside the jar or in your source folder (which will be copied to the bin
folder by your IDE).
You can also navigate up one (or more) folder compared to the folder of the class with the ".."
literal, e.g.:
getClass().getResource("../images/image.jpg");
In this case the image.jpg
file must be in the images
subfolder of the parent folder compared to the folder of the class.
Note: The Class
object whose getResource()
method you call can be acquired like YourClassName.class
or if you want to refer to the class of the current instance: getClass()
.
Upvotes: 3