javajarexecutable-jarimageicon

My jar file won't load images


I am currently writing a program that I need to send to a friend as a jar. The program has images that need to be loaded for the program to work properly and I want it all to be contained in the one jar. Currently it doesn't work from the executable jar or when I run it through command line. It works in netbeans however.

Here's the code I'm using:

To load the image I'm using:

protected ImageIcon createImageIcon(String path, String description)
{
 java.net.URL imgURL = getClass().getClassLoader().getResource(path);
 if (imgURL != null)
 {
     return new ImageIcon(Toolkit.getDefaultToolkit()
                  .getImage(imgURL),description);
 }
 else
 {
     System.err.println("Couldn't find file: " + path);
     return null;
 }
}

for the URL I've also tried just

 getClass().getResource(path)

The line where the image is supposed to be created is:

this.img =createImageIcon(File.separator+"."+File.separator
           +"resources"+File.separator+"tiles"+File.separator+"tile.png","tile");

My jar file is setup with the folder containing the class files and the resource folder both on the top level of it.

I have searched around for ways to resolve this, but I cannot find anything that works.

Thanks.


Solution

  • Your URL will evaluate to "/./resources/tiles/tile.png" which does not make sense (but maybe the ClassLoader that is used when you run from NetBeans tolerates the error.)
    Try dropping the initial "/./". Also you do not need the references to File.separator as the string is treated as a relative URL and the forward slash is always valid.