Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jan 28, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Get Your Graphics Here

If you extend a few AWT classes, you will eventually want to add images to enhance their appearance. Icons for buttons and your own logo in the corner of frames are good examples. But how can you be sure of where the image should be loaded from at run time? The following code will work when the graphics file (a GIF or JPEG) is in the same location as the class file. This could be a local sub-directory for an application, a remote one for an applet, or a JAR file in either situation:
import java.awt.*;
import java.net.*;
import java.awt.image.*;
Image icon = null;
try {
    Class me = getClass();
    URL file = me.getResource("YourIcon.gif");
    Object pixels = file.getContent();
    icon = createImage((ImageProducer)pixels);
catch (Exception ex) {}
The try block protects against the image file not being present, and against its contents not being a recognized image format.
Tom Yarker
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date