devxlogo

Get Your Graphics Here

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.

See also  Monetize TikTok For Your Business
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist