Twitter Updates

Saturday 4 April 2009

Java loading Jar Resources

When moving from running java programs from a directory to running from inside a jar file, I ran into trouble with loading images.

I use to do the following :

fileIconLocation = "toolbarButtonGraphics/general/Edit16.gif";

//http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + imgURL.toString());
return null;
}
}


Once inside the Jar it can not find the file and always returns null.
Replacing getClass() with getClass().getClassLoader() seems to fix the problem.


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

No comments: