MIDP's User Interface Hierarchy: Event Handling

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Created: thiagobrunoms (26 Oct 2009)
Last edited: hamishwillee (01 Aug 2013)

In our sixth part of the MIDP's User Interface Hierarchy series, we discussed about the Item (MIDP's User Interface Hierarchy: Item Components), which can be used in Form-based screens. In the last part of this series, I'll discuss about event handling in the MIDP's LCD user interface.



We cannot imagine a mobile application without user interactions, even if it is to start or stop a MIDlet. Event handling is important to most every MIDlet. In the MIDP, there are two ways for handling events in a J2ME applications: by the Command (javax.microedition.lcdui.Command) class and CommandListener (javax.microedition.lcdui.CommandListener) interface or by using the ItemStateListener (javax.microedition.lcdui.ItemStateListener) interface. These classes are used only to high-level user interface components, such as those discussed in previous articles of this series. Low-level event handling (such as key codes, game actions and pointer events) will not be addressed here.


In short, event handling is the process of recognizing when an event occurs and taking an action accordingly. For instance, when requesting for help - by pressing the help button - the application must display a help message. The event is divided into 3 steps:

1. The hardware (the physical device) recognize that something has occurred: a button was pressed or released, an adapter has been plugged in or removed, etc 2. The software on the device (the application manager) is notified of the event. 3. As a MIDlet developer, we need to precess this message by receiving it from the application manager that is sent to the MIDlet. This message will contain information about the event. Its up to us to decide what to do (e.g., the event may be a request to show a help message on the display).

In order to receive event messages from the application manager, we need to set up what we refer to as a "listener". There are two "listener"interfaces available in the MID Profile: CommandListener and ItemStateListener. As part of the class that implements these interfaces, we need to write the methods commandAction() and/or ItemStateChanged(), respectively. You must treat the event in the body of these methods.

Command Objects

A Command is an object that holds information about an event. A Command object is like a button that you can press or select. In the following figure you can see the "Exit" command.


The following code example shows how to create a new command and handle a command event. The MyForm creates a new Form screen and adds two commands (Ok and Exit). The addCommand method appends a new Command object to the screen.Note that this class also implements CommandListener. That is, if these commands are pressed, the commandAction() method is called. All we need to do is to verify which command is being pressed, by checking their references (arg0 == cmdExit or cmdOk). The second parameter specifies the current displayable that is visible (it can be a TextBox MIDP's User Interface Hierarchy: TextBox, an Alert MIDP's User Interface Hierarchy: Alert, a Form MIDP's User Interface Hierarchy: Form or a List MIDP's User Interface Hierarchy: List).

public class MyForm extends Form implements CommandListener {
private Command cmdOk;
private Command cmdExit;
private MIDlet m;
public MyForm(String title, MIDlet m) {
this.m= m;
cmdOk = new Command("Ok", Command.OK, 0); //creates a new Ok command
cmdExit = new Command("Exit", Command.EXIT, 0); //creates a new Exit command
addCommand(cmdOk); //appends the Ok command to the Form
addCommand(cmdExit); //appends the Exit command to the Form
setCommandListener(this); //sets Form as the CommandListener
* (non-Javadoc)
* @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)

public void commandAction(Command arg0, Displayable arg1) {
if(arg0 == cmdOk) { //checks if the user pressed "Ok"
append("You pressed ok!\n"); //appends the string to the Form
} else if(arg0 == cmdExit) { //checks if the user pressed "Exit"
m.notifyDestroyed(); //destroy app

Our MIDlet only creates a new MyForm screen and sets it to be visible.

public class CommandEx extends MIDlet {
private Display d;
private MyForm f;
public CommandEx() {
d = Display.getDisplay(this);
f = new MyForm("Command Example", this);
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}
protected void pauseApp() {}
protected void startApp() throws MIDletStateChangeException {

The following figures show the example running. After pressing "Ok" three times, we have the "You pressed Ok" message in the screen (three times).

OKExistCommandsExample.jpg OKCommandExample.jpg

In short, to create a command and to handle when a new event occur:

  1. Create a Command object to hold information about an event.
    //Creates a new command with "Exit" as its label, Command.Exit as its type, and 0 as the priority of the command
    Command cmdExit = new Command("Exit", Command.Exit, 0);
  2. Add the Command to a Form, Textbox, List or Canvas.
    Form f = new Form("Command Example");
  3. Add a "listener" to the above Form, Textbox, and so forth

If more than two commands are appended, a Menu command is created. This is where the priority parameter comes in. If we have four commands, such as new Command("Command1", Command.SCREEN, 1);, new Command("Command2", Command.SCREEN, 2);, new Command("Command3", Command.SCREEN, 3); and new Command("Command4", Command.SCREEN, 4);, they will be appended in this order in the Menu command. The following figure depicts this example:


On the other hand, if we change the fourth to be the third command (and visa-versa), we have this scenario ( ... Command("Command3", Command.SCREEN, 4); and ...Command("Command4", Command.Exit, 3); )


Command objects can be one of the following types:

  • Command.OK: A command that is a standard positive answer to a dialog implemented by current screen.
  • Command.EXIT: A command used for exiting from the application.
  • Command.SCREEN: Specifies an application-defined command that pertains to the current screen.
  • Command.CANCEL: A command that is a standard negative answer to a dialog implemented by current screen.
  • Command.HELP: This command specifies a request for on-line help.
  • Command.ITEM: With this command type the application can hint to the implementation that the command is specific to the items of the Screen or the elements of a Choice.
  • Command.STOP: A command that will stop some currently running process, operation, etc.
  • Command.BACK: A navigation command that returns the user to the logically previous screen.

WARNING: The command type only allows the device to locate the command to the correct position, not to "do the job".

Item Objects

A second type of event handling is done through an Item (discussed in MIDP's User Interface Hierarchy: Item Components). As I presented in the last article of this series, you can append as many Item components in a Form screen as possible. As important feature of these Items is that most of them can fire events (event changes). For instance, imagine that a user changed the date of a DateField component. This component can fire a state change event. You can capture this event and act accordingly.

Once you add an Item to a Form, as with Commands, you must add a listener. Once an item has changed its state, an event is sent to an itemStateListener listener. To capture item state changes, you must implement ItemStateListener interface and its required method itemStateChanged().

NOTE 1: StringItem and ImageItem are also subclasses of Item . However, once allocated, these objects are static and thus do not receive/acknowledge events.

NOTE 2: The specification does not require itemStateChanged() to be called on each and every change. That is, if you write a code in your MIDlet to change the date of a DateField, it will not fire an event.

The following code shows the ItemStateChange in action. The idea is to change the label of a date field (announcing that the date has been changed) and to show the letters that the user has pressed in the text field.

//implements ItemStateListener
public class MyForm extends Form implements CommandListener, ItemStateListener {
private Command cmdOk;
private Command cmdExit;
private DateField dateField;
private TextField textField;
private MIDlet m;
public MyForm(String title, MIDlet m) {
this.m= m;
cmdOk = new Command("Ok", Command.OK, 1); //creates a new Ok Command
cmdExit = new Command("Exit", Command.EXIT, 2); //creates a new Exit Command
dateField = new DateField("Date", DateField.DATE); //Creates a new DateField component
textField = new TextField("Text", "", 10, TextField.ANY); //Creates a new TextField component
append(dateField); //appends DateField to the form
append(textField); //appends TextField to the form
addCommand(cmdOk); //adds the Ok command
addCommand(cmdExit); //adds the exit command
setCommandListener(this); //sets a command listener (this form)
setItemStateListener(this); //sets an item state listener (this form)
* (non-Javadoc)
* @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)

public void commandAction(Command arg0, Displayable arg1) {
if(arg0 == cmdOk) {
append("You pressed ok!\n");
} else if(arg0 == cmdExit) {
* (non-Javadoc)
* @see javax.microedition.lcdui.ItemStateListener#itemStateChanged(javax.microedition.lcdui.Item)

public void itemStateChanged(Item arg0) {
if(arg0 == dateField) { //if date field fires an event
dateField.setLabel("New Date changed!"); //sets a new label to the DateField
} else if(arg0 == textField) { //if textField fires an event
append("- you typed: " + textField.getString() + "\n"); //appends what is written in the text field.

DateFieldEmpty.jpg DateFieldEvent.jpg

TextFieldEmpty.jpg TextFieldFired1.jpg TextFieldFired3.jpg TextFieldFired4.jpg

Finally, this last article of the MIDP's series has shown how to use event handling in MIDP. I hope that the MIDP's User Interface Hierarchy series have helped you to build your JavaME application.

This page was last modified on 1 August 2013, at 09:58.
46 page views in the last 30 days.