Thursday, March 18, 2010

J2ME - Alert - How to show images in alerts

We already saw a code example that shows text based Alerts in J2ME. Alert is a way of showing user targeted alert messages in J2ME. You can also add an image or icon to this alert to make it more attractive and more explanatory. This is important to show images in alerts to associate an automatic sense of users to a typical type of message. If alert shows an error and you show a red icon with the Alert, you will automatically pass half the message to the user even before the user reads the message.

Also, for applications that are used in different parts of the world by people from different languages and cultures, images and icons can convey the message better than words.

Here is the code that will show an Alert with an Image included.

Image i = Image.createImage("/cube.png");
Alert a = new Alert("Alert!",  "This is the alert!", i, AlertType.INFO );
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);


A few pointers to elaborate above code. Image is obviously the class that represents images in J2ME. Image is part of javax.microedition.lcdui package. createImage() is a static method of Image class that will load the image file from the MIDlet package.

We will discuss this later in detail but MIDlet applications, when ready for deployment, are compressed in .jar files and .jar files retain the hierarchy of files and folders within the .jar file. In our example, the code is picking a png file named cube.png from /  , the root directory in the jar.

Once the image is loaded, it is passed as an argument of the Alert constructor. There are four arguments. Argument 1 is the title of the Alert, argument 2 is the body text of the alert, argument 3 is the image and last argument is Alert type. We will have more discussion later on the alert types.

Here's the output of the above code.





A word of caution. When loading an image from the file, you must catch IOException that is thrown by Image.createImage() method. You can either catch the exception to show an error message or can throw it in the method's definition where you load this image.


Related J2ME Articles

 

    No comments:

    Post a Comment