0

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

Community
  • 1
  • 1
austinphilp
  • 57
  • 1
  • 9
  • 1
    The jar should contain the icons. By putting them outside of the src directory and using the basic export functions of your IDE, the images were probably not included in the jar file. A jar file is just a zip file, so open it, and see if they're present and in which package. But really, since they're resources that must be loaded by the ClassLoader just like class files, they should be in some package under the src directory (or any other directory that is a source folder in your IDE project) – JB Nizet Aug 12 '14 at 06:27
  • What IDE are you using? – MadProgrammer Aug 12 '14 at 06:27
  • As a (lighter download, more versatile) alternative to images for chess pieces, consider rendering them at run-time from the Unicode glyphs - as seen [here](http://stackoverflow.com/a/18686753/418556). – Andrew Thompson Aug 12 '14 at 06:32
  • Try this 2 links http://stackoverflow.com/questions/8258244/accessing-a-file-inside-a-jar-file and http://stackoverflow.com/questions/403256/how-do-i-read-a-resource-file-from-a-java-jar-file – Saif Aug 12 '14 at 06:41
  • Are you sure the icons are in your jar file? – BetaRide Aug 12 '14 at 06:42

1 Answers1

3

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().

icza
  • 389,944
  • 63
  • 907
  • 827