Java Reference
In-Depth Information
public static Image getImage(Class relativeClass, String filename) {
Image returnValue = null;
InputStream is = relativeClass.getResourceAsStream(filename);
if (is != null) {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
int ch;
while ((ch = bis.read()) != -1) {
baos.write(ch);
}
returnValue = Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
} catch (IOException exception) {
System.err.println("Error loading: " + filename);
}
}
return returnValue;
}
}
Here's how you use the helper class:
Image warnImage = ImageLoader.getImage(LabelJarSample.class, "Warn.gif");
Icon warnIcon = new ImageIcon(warnImage);
JLabel label2 = new JLabel(warnIcon);
Tip Keep in mind that the Java platform supports GIF89A animated images.
GrayFilter Class
One additional class worth mentioning here is GrayFilter . Many of the Swing component
classes rely on this class to create a disabled version of an Image to be used as an Icon . The
components use the class automatically, but there might be times when you need an AWT
ImageFilter that does grayscales. You can convert an Image from normal to grayed out with
a call to the one useful method of the class: public static Image createDisabledImage
(Image image) .
Image normalImage = ...
Image grayImage = GrayFilter.createDisabledImage(normalImage)
You can now use the grayed-out image as the Icon on a component:
Icon warningIcon = new ImageIcon(grayImage);
JLabel warningLabel = new JLabel(warningIcon);
 
Search WWH ::




Custom Search