J2ME User Interface

1) Introduction

User-interface requirements for small handheld devices are different from personal computers. Because comparatively the display size of handheld devices is smaller. That’s why, we cannot follow the personal computers user-interface programming guidelines for handheld devices. In J2ME,the CLDC itself does not define any GUI functionality. The official GUI classes for the J2ME are included in profiles such as the MIDP and are defined by the Java Community Process (JCP). The GUI classes in the MIDP are not based on the Abstract Window Toolkit (AWT). The limited CPU memory of handheld devices, cannot handle the AWT. The MIDP contains its own GUI guidelines. The MIDP GUI consists of high-level and low-level APIs, each with their own set of events. Here we are going to discuss about only High-level API’s.
Contents: (This one itself shows the Device Display Heirarchy)

also read:

  • Display Object
    • Displayable Object
  • DISPLAYABLE : Screen Object
    • TextBox Object
    • Alert Object
    • List Object
    • Form Object
  • FORM : Item Object
    • ChoiceGroup Object
    • DateField Object
    • Guage Object
    • Image and ImageItem Object
    • StringItem Object
    • TextField Object

2) API’s

MIDP offers a high-level API objects for user interface development. This is used to build common user-interface components such as Form s, TextBox etc… This handles most component functionality, such as drawing each component on the screen.

2.1) Display Object

A MIDlet has one instance of a Display object. This object is used to obtain information about the current display and includes methods for requesting the objects being displayed. The Display object is essentially the manager of the device display.Display is represented by the javax.microedition.lcdui.Display class. The Display class is the one and only display manager that is instantiated for each active MIDlet and provides methods to retrieve information about the device’s display capabilities.A reference to the device’s display can be obtained by providing a MIDlet reference to the static getDisplay( ) method in the startApp( ) method of a MIDlet.

public Display getDisplay(MIDlet lMidlet);		

public class firstMidlet extends MIDlet
	firstMidlet( ) { }
	int startApp( ) 
	{ .....
		return 0;}	

Now we have a reference. Then we have to create GUI component. The two forms of the setCurrent() method with this reference as parameter are shown here.

setCurrent(Displayable dispRef);
setCurrent(Alert aRef, Displayable dispRef);

2.1.1) Displayable Object
There is only one Display object per MIDlet, but many objects within a MIDlet may be displayable. A Displayable object is a component that is visible on a device. MIDP contains two subclasses of Displayable: Screen and Canvas.

abstract public class Displayable
public abstract class Canvas extends Displayable
public abstract class Screen extends Displayable	

We can find out that, what is currently being displayed on the device. We can find the types of colors the display object supports.Here are the methods.

public Displayable getCurrent( );

public void boolean isColor( ); //returns TRUE if it supports Color, FALSE if it Supports grayscale
public int numColors( ); //Returns number of colors it supports

2.2) DISPLAYABLE : Screen Object

User interacts with the device through Screen. Screen combines and organizes graphics objects and manages user input through the device. Screens are represented by the javax.microedition.lcdui.Screen object. Then by calling setCurrent( ) they will shown by the Display object.There can be several screens in an application, but only one screen at a time can be visible in a display. There are four types of screens, TextBox, List, Alert, and Form. Screen can have two characteristics: title and ticker.

The title is a string that appears above the screen contents. The following methods are used to set and retrieve the title of the screen.

public void setTitle(String title);
public String getTitle( );	

The Ticker is a image that stays above the title. The Ticker class implements a tickertape. Starting and Stopping the Ticker doesn’t done using methods.The string associated with Ticker scrolls continuously, whose direction of scrolling and the speed of the scrolling depends on the MIDP implementation.The following are the list of methods used in the Ticker.

public void setTicker(Ticker ticker); // To set the Ticker
public Ticker getTicker( ); // To get the Ticker

public Ticker(String string); // Ticker's Constructor.

public String getString( ); //To get the sring Associated with he Ticker
public setString(String s);// To set the sring Associated with he Ticker

setTicker(new Ticker("HI HOW ARE YOU"));//To attach the Ticker to screen

2.2.1) TextBox
TextBox is a screen’s object, using which we can give input and modify the text. TextBox is used when the user needs to give the input for the application. Here is the TextBox’s Constructor.

public TextBox(String title, String text, int maxSize, int constraints); 

The text is used to get the text in the TextBox and maxSize is used to set the maximum size of the TextBox. Some integer constants are used to limit the text in the TextBox such as TextField.ANY , TextField.EMAILADDR ,TextField.NUMBER, TextField.PASSWD, TextField.PHONENUMBER, and TextField.URL. Here are some methods used with TextBox.

public int getConstraints( ); // To get the Current Constraints associated with the TextBox
public void setConstraints(int c);// To set the Constraints for TextBox

public int getMaxSize( ); // To get the Maximum Size of TextBox
public void setMaxSize(int size); // To set the Maximum Size of TextBox
public String getString( ); // To get the Text in the TextBox
public void setString(String s); // To set the Text in the TextBox

public int size( ); // To Get the number of Characters in the TextBox

/* Text Manipulation Methods */

public void delete(int offset, int length); // To delete some text
public void insert(char[] texts, int offset, int length, int position); // To Insert text
public void replace(String str, int position); // To replace the text
public void setChars(char[] texts, int offset, int length); // To set the characters

public int getCaretPosition(  ); // To get the Cursors position

2.2.2) Alert
Alert is a screen which contains text or image. It is used to show the errors and exceptions. A modal alert is a alert which need confirmation from user to close it.But the timed alert doesnt need the confirmation from user.It shows the error for certain amount of time and terminates.Here is the constructor for Alert:

public Alert(String name);
public Alert(String name, String message, Image msgImage, AlertType errorType);	

We can use a timeout value for displaying the Alert message, means how much time the Alert message displays. Initially we can set the timeout and later we can change it. If we want to know the current timeout value we can get it.Similarly we can set and get the Image and String values associated with the Alert.Here are the methods for the same.

public int getDefaultTimeout( );// To get the current default timeout value
public int getTimeout( );		//To get the current timeout value
public void setTimeout(int t);	//To set the timeout value
Alert alert = new Alert("Error Message"); // To create a new Alert
alert.setTimeout(5000); 		// Sets the timeout for 5000 milli seconds
alert.setTimeout(Alert.FOREVER); // To display the alert until user closes it.
public Image getImage( ); 		// To get the image associated with the Alert
public String getString( ); 	// To get the String associated with the Alert
public void setImage(Image "alert.png"); //To set the image associated with the Alert
public void setString(String "Spawning Error"); // To set the String associated with the Alert

The AlertType class has provided with five differet types of alerts: AlertType.ERROR, AlertType.ALARM, AlertType.CONFIRMATION, AlertType.WARNING, and AlertType.INFO. . Here are some methods to set and get the Alert Types.

public AlertType getType( );
public void setType(AlertType AlertType.CONFIRMATION);	

Similarly we can create specific types of alerts as timedAlert or modalAlert.And using the same methods we can set and get the timeouts for them.

Alert timedAlert = new Alert ("Warning", "Clear It", null, AlertType.WARNING); // Creating
TimedAlert.setTimeout(5000); // to set the timeout for timedAlert
Display.setCurrent(timedAlert, timed); // To set the timedAlert as current alert

Alert modalAert = new Alert("Alarm", "Reminder", null, AlertType.ALARM);// Creating
modalAlert.setTimeout(alert.FOREVER); // modalAlert need manual dismissal
display.setCurrent(modalAlert, timed);// To set the modalAlert as current alert

2.2.3) List
List is a screen which is having some choices for selection. User has to select one of the choices explicitly. Its constructors are:

public List(String name, int listType);
public List(String name, int listType, String[] stringElements, Image[] imageElements);	

There are three types of list types, MULTIPLE , EXCLUSIVE, and IMPLICIT .

  • EXCLUSIVE type of list allows only one selection.
  • IMPLICIT type of list is a list where the choice is implicitly selected.
  • MULTIPLE type of list allows more than one selection of choices.

Here is an example

List list = new List("select one or more", Choice.MULTIPLE);	

We can append, insert, or replace choices in the list. For a choice the text associated to it is mandatory and image associated with it is optional. We can delete the index associated t a choice. We can get text and image associated to a choice. Here are the methods:

public int append(String string, Image image); // To append into the list
public void insert(int choiceNo, String string, Image image); // To insert into the ist
public void set(int choiceNo, String string, Image image);//To replace the choice in the list

int open = list.append("OPEN", null); // open is index for the choice "OPEN"

public void delete(int index); // To delete an index

public String getString(int index); // To get the text associated to the choice with its index
public Image getImage(int index);//To get the image associated to the choice with its index

public boolean isSelected(int index); // To know which is selected in the list
public setSelectedIndex(int index, boolean bool); // To select the choice

public int getSelectedFlags(boolean[] selectedArray); // To set the selection state of the entire list
public void setSelectedFlags(boolean[] selectedArray); // To modify the one that has been passed in	

2.2.4) Form
Forms used to combine multiple components into one screen. It is a screen that contains items. Its constructors are:

public Form(String str);
public Form(String str, Item[] items);	

It will arrange its components as a list. Like the choices within a list, items within a form can be edited using insert, append, and delete.Here are some examples.

public int append(Image img); //appends an object that subclasses the Item object	
public int append(Item item);
public int append(String str); //append a generic string	
public void delete(int itemNum); //deletes the item at the given position
public Item get(int itemNum);//access any item in the form at its given position
public void insert(int itemNum, Item item);//inserts an item in the form
public int set(int itemNum, Item item);//setting the item referenced by itemNum
public int size( );//find the current number of items that are in the form	

The GUI components that can be placed on a form are: ChoiceGroup, DateField, Gauge, ImageItem, StringItem, and TextField.

2.3) FORM : Item Object

The Item abstract class acts as the base class for all components that can be placed on a form. All Item objects have a label:

public String getLabel( );
public void setLabel(String s);	

2.3.1) ChoiceGroup
A ChoiceGroup object represents a list of selectable choices to be placed on a Form object. It implements the Choice interface. In this object single choice can be made, or it may allow multiple choices. It has two constructors:

public ChoiceGroup(String label, int choiceType);
public ChoiceGroup(String label, int choiceType, String[] stringElements, Image[] imageElements);

The first constructor is used to create an empty choice group, specifying its label and type. Here two choices are available: EXCLUSIVE and MULTIPLE. The second constructor can be used to create a new choice group, specifying its title and type.We can insert, append, or replace choices in this.Each choice has an integer index that represents its position in the list. The first choice starts at 0 and extends to the current size of the list minus one. It has the following methods.

public int append(String stringElement, Image imageElement);
public void insert(int index, String stringElement, Image imageElement);
public void set(int index, String stringElement, Image imageElement);

Here are some examples.

int save = list.append("save", null);

public void delete(int index);//delete any index in the choice group
public String getString(int index);//retrieve the string element
public Image getImage(int index);//retrieve the image element

public int getSelectedIndex( ); 
public boolean isSelected(int index);

public setSelectedIndex(int index, boolean selected);//set the currently selected index
public int getSelectedFlags(boolean[] selectedArray); //set the selection state of the entire choice group
public void setSelectedFlags(boolean[] selectedArray);

ChoiceGroup choices = new ChoiceGroup("Method of payment",Choice.EXCLUSIVE);
choices.append("aaa", null); //adds several new choices(Do the same for all)
choices.delete(15);//delete the 15th choice. Similarly insert and append

Choice can be displayed using:

setCurrent( ).
Form form = new Form("Select");

2.3.2) DateField
A DateField object is a component for representing date and time information. It can be configured to accept date or time information. It has the following constructors:

public DateField(String label, int mode);
public DateField(String label, int mode, TimeZone timeZone);	

The firstone is used to create a DateField object with the specified label and mode. It has some static fields: DateField.DATE, DateField.TIME, or DateField.DATE_TIME. The DateField.DATE input mode used to set date information, DateField.TIME for clock time information, and DateField.DATE_TIME for both. This one has the following methods.

public Date getDate( )
public int getInputMode( )
public void setDate(Date date);
public void setInputMode(int mode);

public String toString( ); // output a string-based copy of the date or time 

DateField date = new DateField("date", DateField.DATE); //creates a DateField object

/* display a date field */ 

Form form = new Form("Date Info");

/* Initialize the date and time before displaying the component */

d = new DateField("Today: ", DateField.DATE);
d.setDate(new Date( ));
form = new Form("Date & Time");

/* Creating a DateField object where the time zone is GMT */

DateField date = new DateField("date", DateField.DATE,TimeZone.getTimeZone("GMT"));

/* Using the default time zone */

DateField date1 = new DateField("date", DateField.DATE);
DateField date2 = new DateField("date", DateField.DATE, TimeZone.getDefault( ));

2.3.3) Gauge
A Gauge object represents a bar graph display that can be used within a form. It has the following constructor:

public Gauge(String label, boolean interactive, int maxValue, int initialValue);

This is used to create a new Gauge object with the given label, in interactive or non-interactive mode, with the given maximum and initial values. In interactive mode, we can modify the gauge’s current value; in non-interactive mode, we cannot change the value.

	public boolean isInteractive( );//Whether the gauge is currently in interactive mode or not
public int getMaxValue( ); //access the Max value
public int getValue( ); //access the current value
public void setMaxValue(int maxValue); //set the Max value
public void setValue(int value);

/* interactive gauge where the maximum value is 20 and the initial value is 0 */

Gauge gauge = new Gauge("graph", true, 20, 0);

/* placing guage on a Form component */

Form form = new Form("item");

/* non-interactive gauge that reflects  the progress bar */

Display display = Display.getDisplay(this);
Gauge progressbar = new Gauge("Progress", false, 20, 9);
Form form = new Form("Configuring App);

2.3.4)Image and ImageItem
An ImageItem object is an image component that contains a reference to an Image object. Images can either be immutable or mutable. Immutable images are generally created by loading image data.They cannot be modified after creation. Mutable images, are created in off-screen memory and can be modified. A mutable image can be created using static createImage( ) methods of the Image class.

public static Image createImage(int width, int height);

/* Three static createImage( ) methods used to create immutable images */

public static Image createImage(Image image);
public static Image createImage(String name);
public static Image createImage(byte[] imageData, int imageOffset,int imageLength);

/* Creating an immutable image */

Image image = Image.createImage("image1.png");

/* Placing an Image in a Form object */

Form form = new Form("Form");

/* Measuring the height, width, and mutable status of a image */

public int getHeight( );
public int getWidth( );
public boolean isMutable( );

/* Getting the Graphics object of an image */

public Graphics getGraphics( );

/* Creating an ImageItem object using the ImageItem constructor */

public ImageItem(String label, Image img, int layout, String altText);

/* Methods to access the properties of the ImageItem constructor */ 

public String getAltText( );
public Image getImage( );
public int getLayout( );
public void setAltText(String altText);
public void setImage(Image img);
public void setLayout(int layout);

/* Creating the ImageItem object using ImageItem constructor */

Image img = Image.createImage("/Example.png");
ImageItem imageItem = new ImageItem("Image", img, ImageItem.LAYOUT_CENTER, "img");
Form form = new Form("Example");

2.3.5) StringItem
A StringItem object is a text component item that contain a string, label, and contents. We cannot edit the string but we can edit the label and contents.Here is the constructor..

public StringItem(String label, String contents);

/* Creating a StringItem object */

StringItem si = new StringItem("string", "contents");

public void setText(String s); // Set the StringItem contents
public void setLabel(String l);// Set the label of the StringItem
public String getText( );// Get the StringItem contents
public String getLabel( );//Get the label of the StringItem 

/* Creating a StringItem object placing it within a Form object */

Display display = display.getDisplay(this);
StringItem si = new StringItem("String item:\n", "Hello World!");
Form form = new Form("Greetings");

2.3.6) TextField
TextField object is an editable text component.A TextField has a capacity, which is the number of characters that can be stored in the object. There must be a boundary on the maximum size,which we can get using getMaxSize( ). TextField is used when the MIDlet requires input from the user. A TextField has the constructor:

public TextField(String label, String text, int maxSize, int constraints); 	

The constraints field is used to limit the user input like TextField.ANY, TextField.EMAILADDR, TextField.NUMBER, TextField.PASSWD, TextField.PHONENUMBER, and TextField.URL. Here we have some examples..

public int getConstraints( ); //Retrieve the current constraints
public void setConstrants(int c);//Set the current constraints

public int getMaxSize( ); //Gets Maxsize
public void setMaxSize(int size);// Sets Maxsize

public String getString( ); //Retrieve the text in the TextField
public void setString(String s);//Set the text in the TextField

public int size( );//To get the number of characters in the TextField

/* delete, insert, and replace */ 

public void delete(int offset, int length);
public void insert(char[] data, int offset, int length, int position);
public void insert(String src, int position);
public void setChars(char[] data, int offset, int length);

public int getCaretPosition( ); //To Find the position of the caret or insertion beam

/* Typical sign in form */

Display display = Display.getDisplay(this);
TextField userName = new TextField("LoginID:", "", 10, TextField.ANY);
TextField password = new TextField("Password:", "", 10, TextField.PASSWORD);
Form form = new Form("Sign in");

3) Conclusion

Herewith we discussed about the Graphical user interface concepts in J2ME. Try the example programs with the help of the methods discussed above.These method names are very much standard and easy to remember, so one time practice is enough to become efficient in J2ME GUI Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!