Programming Tutorials

Image and ImageItem sample program in J2ME

By: Norman Chap in J2ME Tutorials on 2007-09-16  

Here's an example J2ME program that demonstrates the use of Image and ImageItem:

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.midlet.*;

public class ImageItemExample extends MIDlet {
    private Display display;
    private Form form;
    private ImageItem imageItem;
    private Image image;

    public void startApp() {
        display = Display.getDisplay(this);
        form = new Form("Image Item Example");
        try {
            // load the image from file
            image = Image.createImage("/example.png");
            // create the image item
            imageItem = new ImageItem(null, image, ImageItem.LAYOUT_CENTER, "Example Image");
            // add the image item to the form
            form.append(imageItem);
        } catch (Exception e) {
            // handle any exceptions thrown
            e.printStackTrace();
        }
        // show the form on the display
        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

This program loads an image from a file and creates an ImageItem from it. The ImageItem is then added to a Form, which is displayed on the screen using the Display class.

The ImageItem constructor takes four arguments:

  1. A label for the item (in this case, null is used to indicate no label)
  2. The Image object to display
  3. The layout style for the item (ImageItem.LAYOUT_CENTER is used to center the image)
  4. A description of the image (in this case, "Example Image" is used)

The program assumes that there is an image file named "example.png" in the project directory. If the image file does not exist or cannot be loaded, an exception will be thrown and printed to the console.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)