Loading Icons and Graphics in Jars
[Previous] [Main] [Next]

Loading Icons and Graphics in Jars.

You must use a classloader. This is demonstrated in the following static class that replaces the coffee cup on your forms.

Note: There are three interesting things here.
1. Code to find the folder that your application is running from.
2. Code to run from an IDE or a JARS environment
3. JDialog note: You must run SUPER() at the beginning of your class or the icon cannot be set.

package com.halepringle.deliverprc

/** Description - replace the coffee cup icon on a frame with a gif value you choose.
* @param - JFrame - frame to attach icon to
* @param - String - gif name for image in the images/ folder under the root of your application
* @return - nothing
* This method finds the path to the images folder or the jar and loads * the image with the appropriate loader.
* NOTE: For JDialog, the JDialog must have a parent frame passed in.
* The first command MUST be super({frame}, "{Frame Title}",true);
* then you can set the frame equal to a local fields and include * SetIcon({frame},"{name-of-gif.gif}");
* Without the SUPER command the SetIcon class will not work.
*/

public void static SetIcon(JFrame jF, String gifName){
if (jF == null) { return; } // don't even try - it will blow
URL imgPath1;
String imgPath2, imgPath3,iniPath;
imgPath1 = SetIcon.class.getProtectionDomain().getCodeSource().getLocation();
// imgPath1 will now contain a URL that points to the folder your application is running from. Note: SetIcon.class is the current class!
imgPath2 = imgPath1.toString();
// imgPath2 = contains the string version of the URL It will begin with file: or http:
imgPath2 = imgPath2 + "images/"+gifName;
// NOTE: This assumes that all your gifs are in one folder under the root of your main folder.
javax.swing.ImageIcon img ;
if (imgPath2.indexOf(".jar")>0){ // use classloader if in a jar
ClassLoader cl = this.getClass().getClassLoader();
img = new javax.swing.ImageIcon(cl.getResource("images/"+gifName));
} else{ // just load the image if you not in a jar
img = new javax.swing.ImageIcon(imgPath2);
}
jF.setIconImage(img.getImage());
}