March 2002 Technical Tip Dynamically load .jpeg images from Java Programs

This month's tip our first demonstrates how to dynamically load .jpeg images from Java programs. The trick is to use the setIcon() method of the JLabel class.

The sample applet opens with the following display:

When the user clicks the Heads button, the following is displayed:

Likewise, the user can click the Tails button to see the tails image, or click the Clear button to clear the image.

The complete applet is available for download (see http://www.caliberdt.com/tips/ImageApplet.java) but here's the meat of it:

public void actionPerformed(ActionEvent e)
{
   if (e.getSource() == btnHeads)
      doHeads();
   else if (e.getSource() == btnTails)
      doTails();
   else if (e.getSource() == btnClear)
      doClear();
}

private void doHeads()
{
   showImage("heads.jpg");
}

private void doTails()
{
   showImage("tails.jpg");
}

private void doClear()
{
   lblImage.setIcon(null);
}

private void showImage(String s)
{
   lblImage.setIcon( new ImageIcon(
      java.awt.Toolkit.getDefaultToolkit().getImage(s) ) );
}

The actionPerformed() method directs processing to the appropriate method based upon the button clicks. Note that the doHeads() and doTails() methods pass the name of the file containing the .jpeg image to the showImage() method. The showImage() method uses the passed filename to retrieve the image, ultimately using the setIcon() method of the JLabel class to show the image.

Download heads.jpg

Download tails.jpg

This tip is presented with a working application. You'll find that our classes like our tips are loaded with examples, making for a more enjoyable and productive learning experience. Caliber Data Training is pleased to offer training in Java programming. We hope you will consider us when deciding upon a training provider.


Go to the articles index. Written by Bill Qualls. Copyright © 2003 by Caliber Data Training 800.938.1222