Image and ImageItem sample program in J2ME

By: Norman Chap Viewed: 153362 times  Printer Friendly Format    

Several MIDP UI components support the display of an image. Here, a form contains an ImageItem component, which displays an image.

The constructor creates an image object and passes it to the UI component for display. Notice that the path specification for the image is relative to the resource directory of this project under the J2ME Wireless Toolkit installation.

The program below demonstrates the use of the ImageItem MIDP UI component class. An ImageItem is a subclass of Item, so it must be placed in a Form as demonstrated by the listing. Before you can display an image, you must first create an image object. The javax.microedition.lcdui.Image class defines images. To instantiate Image, specify the path name of an image file. Image files must be stored in the Portable Network Graphics (PNG) format. J2ME supports the manipulation of images in this format only.

Notice in the program below that the path name of the image file is relative to the res/ directory of the UIComponents project directory. The res/ directory contains all resource files, including image files. If you place your images elsewhere, they will not be found, and your program will throw an IOException when it tries to open the file.

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
This class demonstrates the use of the MIDP UI
ImageItem class.
@see javax.microedition.lcdui.ImageItem
public class ImageItemDemo extends Form
implements CommandListener
private ImageItem imageItem;
@throws IOException if the specified image resource
cannot be found.
public ImageItemDemo() throws IOException
super("ImageItem Demo");
String path = "/bottle80x80.png";
Image image = Image.createImage(path);
imageItem = new ImageItem("Ship in a bottle",
"Image not found");
instance = this;

The constructor builds an ImageItem using the Image object just created. The constructor parameters are the title string that displays above the image, the image object, the image placement directive, and a text string to be displayed in case the image can't be displayed for some reason.

The ImageItem class is the only class that provides layout control for images, but several other MIDP UI components use images, too.

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)

Comment on this tutorial