Sie sind auf Seite 1von 23

J.E.D.I.

Chapter 03
High Level User Interface
3.1 Objectives
After finishing this lesson, the student should be able to:
know the advantages and disadvantages of using high-level and low-level UI classes
design MIDlets using the high-level UI components
identify the different sub-classes of Screen
know the different Items that can be put into a Form object

3.2 MIDP User Interface


The MIDP user interface was designed for mobile devices. MIDP applications are displayed
in a limited screen area. Device memory is also a factor since mobile devices only have a
small memory.
With varying kinds of mobile devices, from different models of mobile phones to PDAs, the
MIDP user interface was designed to be flexible enough to be usable in all of these devices.
MIDP has classes that handles high-level and low-level user interface functions. High-level
UI classes are designed to be flexible. The appearance of these components is not defined
in the specifications. The actual screen appearance of these components varies from device
to device. But the programmer is assured that the behavior of the high-level UI
components is the same in all specifications-compliant implementations.

High Level UI

Low-Level UI

highly portable across devices

may be device-specific

look and feel is the same as device

application specific look and feel

interactions like scrolling are encapsulated

must implement own navigation

cannot define actual appearance

can define actual appearance on pixel level

no access to device specific features

access to low-level input like key presses

Figure 1: High-Level UI vs. Low-Level UI

Mobile Application Development

J.E.D.I.

3.2.1

The Display

The heart of the MIDP user interface is the Display. There is one and only one instance of
Display per MIDlet. The MIDlet can get a reference to the Display object by using the static
Display.getDisplay() method, passing a reference to the MIDlet instance.
The MIDlet guarantees the Display object will not change within the MIDlet's instance's
existence. This means that the variable returned when you call getDisplay() is the same
and it will not matter if you called it within startApp() or destroyApp() (see Figure Midlet
Life Cycle).

3.2.2. Displayable
Only one Displayable is displayed at a time. By default, a Displayable is not visible on the
Display. A Displayable can be displayed by calling the setCurrent() method of the Display
instance. The setCurrent() method must be called at the start of the application, otherwise
a blank screen is displayed or the application will not start.

Figure 2: MIDlet Life Cycle


The startApp method of the MIDlet is one place where we can put a call to setCurrent().
But we must take into consideration that the startApp() can be called more than once in
the MIDlet's existence. Once the MIDlet is paused by a call to pauseApp(), maybe by an
incoming phone call, the startApp() may be called again (after the phone call). So by
calling the setCurrent() in the startApp() method, we may be obscuring the previous
screen displayed prior to being paused (by the phone call).
A Displayable can have a title, a set of Commands, a commandListener and a Ticker.

Mobile Application Development

J.E.D.I.

Figure 3: Properties of a Displayable

3.2.3

Title

A Displayable has a title associated with it. The position and appearance of the title is
device specific and can only be determined by the device the application is running on. A
title is attached to a Displayable by calling setTitle(). Calling this method will immediately
update the title of the Displayable. If the Displayable is currently displayed on the screen,
the MIDP specification states that the title should be changed by the implementation "as
soon as it is feasible to do so".
Passing a null parameter to setTitle() removes the title of a Displayable. Changing or
removing a title from a Displayable may affect the size of the area available for the
Displayable's content. If a change in display area size occurs, the MIDlet will be notified
via the sizeChanged() callback method.

3.2.4

Command

Because of limited screen size, MIDP does not define a dedicated menu bar. In place of the
menu bar, MIDlets have Commands. A Command is usually implemented by the MIDP
implementation as a soft key or an item in a menu. A Command object only contains
information about the action to be taken when it is activated. It does not contain code that
will be executed when it is selected.
The commandListener property of a Displayable contains actions that are to be executed
upon the Commands activation. The commandListener is an interface that specifies a

Mobile Application Development

J.E.D.I.

single method:
public void commandAction(Command command, Displayable displayable)
The mapping of Commands on the device depends on the number of available soft or
programmable buttons on the device. If the number of Commands can not fit in all of the
soft buttons, the device may put some or all of the Commands into a menu and map this
menu to a soft button with a label "Menu".
Command exitCommand = new Command("Exit", Command.EXIT, 1);
Command newCommand = new Command("New Item", Command.OK, 1);
Command renameCommand = new Command("Rename Item", Command.OK, 1);
Command deleteCommand = new Command("Delete Item", Command.OK, 1);
...
list.addCommand(exitCommand);
list.addCommand(newCommand);
list.addCommand(renameCommand);
list.addCommand(deleteCommand);
Figure 4: Source for mapping Commands into a Displayable

Figure 5: Sample display of mapping multiple Commands


A Command has a short label, an optional long label, a type, and a priority.
Command Label
The assumed small screen size of the target device is always a factor when developing

Mobile Application Development

J.E.D.I.

MIDP applications. For Command labels, this assumption is also applicable. Command
labels should be short, yet descriptive, so that it will fit on the screen and still be intelligible
to the user.
When the long label is specified, it will be displayed whenever the system implementation
sees that it is appropriate. There is no API call that will specify which label is to be
displayed. It is also possible that some Commands will have a short label displayed while
other Commands on the same screen will have their long labels displayed.
Command Type
The way a command is presented on the device is device-dependent. A programmer can
specify the type of the Command. This type will serve as a hint on where to put the
command. There is no way a program can strictly specify where a command should be
placed on the screen.
The different kinds of Command types are:

Command.OK, Command.BACK,
Command.CANCEL, Command.EXIT,
Command.HELP, Command.ITEM,
Command.SCREEN, Command.STOP

Figure 6: Commands display differently in different phone implementations


Command Priority

Mobile Application Development

J.E.D.I.

The application may specify the importance of Commands in the priority property. This is
an integer property and a lower number means greater importance. The priority property
is also just a hint on where the Command should be placed. The implementation usually
determines the position of a Command by its type. If there are more than one Command
of the same type, the priority will normally be considered in the placements of the
commands.

3.2.5

CommandListener

CommandListener is an interface with a single method:

void commandAction(Command command, Displayable displayable)


The commandAction() method is called when a Command is selected. The command
variable is a reference to the Command that was selected. displayable is the Displayable
(or Screen) where the Command is located and where the select action happened.
The commandAction should return immediately, otherwise the application execution may
be blocked. This is because the MIDP specifications do not require implementations to
create a separate thread for event delivery.

3.2.6

Ticker

The ticker is a line of text continuously scrolling across the display. The constructor method
of the Ticker accepts the text String property to be displayed. It only has two other
methods, the getter and setter for this text: String getString() and void setString(String
text). There is no way the application can control the speed and direction of the scrolling
text. The scrolling cannot be paused nor stopped.
If a line break is embedded into the text, it will not be displayed on the screen. All text
lines will be displayed as a single line of scrolling text.
A Ticker is attached to a Displayable by calling setTicker(). If a Ticker is already attached
to the Displayable, it will be replaced by the new Ticker in the parameter.
Passing a null parameter to setTicker() removes any attached Ticker from a Displayable.
Removing a Ticker from a Displayable may affect the size of the area available for the
Displayable's content. If a change in display area size occurs, the MIDlet will be notified
via the sizeChanged() callback method.
Displayable objects may share one instance of a Ticker.

Mobile Application Development

J.E.D.I.

3.2.7

Screen

The Screen is the main abstract class used for high-level UI while the Canvas is the abstract
Displayable class for low-level UI.
There are four subclasses of the abstract class Screen: Form, TextBox, List and Alert.

Figure 7: Displayable Class Hierarchy

3.2.8

Item

Items are components that can be put into a container, like a Form or an Alert. An item
can have the following properties:

Property

Default Value

Label

specified in the subclass constructor

Commands

none

defaultCommand

null

ItemCommandListener

null

Layout directive

LAYOUT_DEFAULT

Preferred width and height

-1 (unlocked)

Mobile Application Development

J.E.D.I.

Figure 8: Item Class Hierarchy


The layout directive specifies the layout of the Item within the Form. Layout directives may
be combined using the bitwise OR operation (|). However, some directives are mutually
exclusive. These horizontal alignment directives are mutually exclusive:
LAYOUT_LEFT
LAYOUT_RIGHT
LAYOUT_CENTER
The following vertical alignment directives are also mutually exclusive:
LAYOUT_TOP
LAYOUT_BOTTOM
LAYOUT_VCENTER
The other layout directives (not mutually exclusive) are:
LAYOUT_NEWLINE_BEFORE
LAYOUT_NEWLINE_AFTER
LAYOUT_SHRINK
LAYOUT_VSHRINK
LAYOUT_EXPAND
LAYOUT_VEXPAND
LAYOUT_2

3.3 Alert
An Alert is a screen that can display a text and an image. An alert is a component for
displaying an error, a warning, display text and image information, or to get confirmation
from the user.
The Alert is displayed for a specified period of time. This time is set using the setTimeout()
method and is specified in milliseconds unit. It can be made to be displayed until the user
activates a command ("Done") by specifying a special timeout of Alert.FOREVER.
The Alert can also display a Gauge component (see Gauge Item) as an indicator.
When an alert contains text that does not fit a screenful and must be scrolled, the Alert is
automatically set to modal (timeout is set to Alert.FOREVER).

Mobile Application Development

J.E.D.I.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class AlertExample extends MIDlet implements CommandListener {


Display display;
Form mainForm;
Command exitCommand = new Command("Exit", Command.EXIT, 0);
Command okCommand = new Command("Ok", Command.OK, 0);
Gauge gauge = new Gauge(null, false, 5, 0);
Command[] commands = {
new Command("Alarm", Command.OK, 0),
new Command("Confirmation", Command.OK, 0),
new Command("Info", Command.OK, 0),
new Command("Warning", Command.OK, 0),
new Command("Error", Command.OK, 0),
new Command("Modal", Command.OK, 0)
};

Alert[] alerts = {
new Alert("Alarm Alert",
"Example of an Alarm type of Alert",
null, AlertType.ALARM),
new Alert("Confirmation Alert",
"Example of an CONFIRMATION type of Alert",
null, AlertType.CONFIRMATION),
new Alert("Info Alert",
"Example of an INFO type of Alert",
null, AlertType.INFO),
new Alert("Warning Alert",
"Example of an WARNING type of Alert, w/ gauge indicator",
null, AlertType.WARNING),
new Alert("Error Alert",
"Example of an ERROR type of Alert, w/ an 'OK' Command",
null, AlertType.ERROR),
new Alert("Modal Alert",
"Example of an modal Alert: timeout = FOREVER",
null, AlertType.ERROR),
};

public AlertExample(){

Mobile Application Development

J.E.D.I.

mainForm = new Form("JEDI: Alert Example");

mainForm.addCommand(exitCommand);
for (int i=0; i< commands.length; i++){
mainForm.addCommand(commands[i]);
}
mainForm.setCommandListener(this);

// Add a gauge and set the timeout (milliseconds


alerts[3].setIndicator(gauge);
alerts[3].setTimeout(5000);

// Add a command to this Alert


alerts[4].addCommand(okCommand);

// Set this alert to Modal


alerts[5].setTimeout(Alert.FOREVER);
}

public void startApp() {


if (display == null){
display = Display.getDisplay(this);
display.setCurrent(mainForm);
}
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d){


if (c == exitCommand){
destroyApp(true);
notifyDestroyed(); // Exit
}
for (int i=0; i<commands.length; i++){
if (c == commands[i]){
display.setCurrent(alerts[i]);
}
}

Mobile Application Development

10

J.E.D.I.

}
}

INFO Alert

Modal Alert

Alert w/ gauge indicator

Figure 9: Different types of Alert

3.4 List
The List is a subclass of Screen containing a list of choices. A List can be of three types:
IMPLICIT, EXCLUSIVE or MULTIPLE.
If the List is IMPLICIT and the user executes the "select" button, commandAction() of the
List's commandListener would be called. The default command is List.SELECT_COMMAND.
getSelectedIndex() returns the index of the currently selected element, for the IMPLICIT
and EXCLUSIVE types. For the MULTIPLE type, getSelectedFlags() returns an array of
boolean containing the state of the elements. isSelected(int index) returns the state of the
element in the given index position.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class ListExample extends MIDlet implements CommandListener {


Display display;
List list;
Command exitCommand = new Command("Exit", Command.EXIT, 1);
Command newCommand = new Command("New Item", Command.OK, 1);

Mobile Application Development

11

J.E.D.I.

Command renameCommand = new Command("Rename Item", Command.OK, 1);


Command deleteCommand = new Command("Delete Item", Command.OK, 1);
Ticker ticker = new Ticker(
"JEDI - Java Education and Development Initiative");

public ListExample(){
list = new List("JEDI: List Example", List.IMPLICIT);
list.append("List Item #1", null);
list.append("List Item #2", null);
list.append("List Item #3", null);

list.setTicker(ticker);

list.addCommand(exitCommand);
list.addCommand(newCommand);
list.addCommand(renameCommand);
list.addCommand(deleteCommand);
list.setCommandListener(this);
}

public void startApp() {


if (display == null){
display = Display.getDisplay(this);
display.setCurrent(list);
}
}

public void pauseApp() {


}

public void destroyApp(boolean unconditional) {


}

public void commandAction(Command c, Displayable d){


if (c == exitCommand){
destroyApp(true);
notifyDestroyed(); // Exit
}
if (c == List.SELECT_COMMAND){
int index = list.getSelectedIndex();

Mobile Application Development

12

J.E.D.I.

String currentItem = list.getString(index);


// do something
}
}
}

List.IMPLICIT

List.EXCLUSIVE

List.MULTIPLE

Figure 10: Types of List

3.5 Text Box


A TextBox is a sub-class of Screen that can be used to get text input from the user. It
allows the user to enter and edit text. It is similar to a TextField (see TextField Item)
because it can have input constraints and input modes. Its difference with the TextField is
that the user can input a new line (when the input contraint is set to ANY).
The contents of the TextBox can be retrieved using the getString() method.

Mobile Application Development

13

J.E.D.I.

Figure 11: TextBox type ANY (multi-line)

Figure 12: TextBox with PASSWORD modifier

3.6 Form
The Form is a subclass of Screen. It is a container for subclass Items, such as TextField,
StringItem, ImageItem, DateField and ChoiceGroup. It handles the layout of these
components. It also handles traversal among the components and scrolling of the screen.
Items are added and inserted to a Form using the append() and insert() methods,
respectively. Items are deleted using the delete() method. Items can be replaced using
the set() method.
Items are referenced using an zero-based index.

Mobile Application Development

14

J.E.D.I.

3.7 ChoiceGroup
The ChoiceGroup item is a group of selectable choices. The choice may contain a text, an
image or both.
The choices may be EXCLUSIVE (only one choice can be selected) or MULTIPLE (multiple
choices can be selected at a time). If a ChoiceGroup is of type POPUP, only one choice is
displayed. A popup selection will be displayed when this item is selected. From this popup
selection, the user may select his choice. The choice displayed is always the selected
choice.
getSelectedIndex() returns the index of the currently selected element of the
ChoiceGroup. getSelectedFlags() returns an array of boolean corresponding to the state
of the elements of the ChoiceGroup. isSelected(int index) returns the state of the element
in the given index position.

choiceForm = new Form("Choice Group Types");


choiceForm.addCommand(exitCommand);
choiceForm.setCommandListener(this);

choiceExclusive = new ChoiceGroup("Exclusive", Choice.EXCLUSIVE);


choiceExclusive.append("Male", null);
choiceExclusive.append("Female", null);
choiceForm.append(choiceExclusive);

choiceMultiple = new ChoiceGroup("Multiple", Choice.MULTIPLE);


choiceMultiple.append("Apple", null);
choiceMultiple.append("Orange", null);
choiceMultiple.append("Grapes", null);
choiceForm.append(choiceMultiple);

choicePopup = new ChoiceGroup("Popup", Choice.POPUP);


choicePopup.append("Asia", null);
choicePopup.append("Europe", null);
choicePopup.append("Americas", null);
choiceForm.append(choicePopup);

Mobile Application Development

15

J.E.D.I.

Figure 13: Types of Choice Group

3.8 Date Field


The DateField component is used for date and time input from the user. It may contain a
date entry (mode DATE), a time entry (mode TIME) or both (mode DATE_TIME).
The getDate() method returns the current value of the item. It will return null if the item
is not initialized. If the mode of the DateField is DATE, the time component of the return
value is set to zero. If the mode is TIME, the date component is set to "January 1, 1970".

dateForm = new Form("DateField Modes");


dateForm.addCommand(backCommand);
dateForm.setCommandListener(this);

DateField dateonly =
new DateField("Birthday (DATE)", DateField.DATE);
DateField timeonly =
new DateField("Set Alarm (TIME)", DateField.TIME);
DateField datetime =
new DateField("Departure (DATE_TIME)", DateField.DATE_TIME);

dateForm.append(dateonly);
dateForm.append(timeonly);

Mobile Application Development

16

J.E.D.I.

dateForm.append(datetime);

DateField input modes

Selecting a date

Time input

Figure 14: DateField modes and input screens

3.9 String Item


A StringItem is a read-only component. It is composed of a label and a text.
The StringItem optionally accepts an appearance mode parameter. The appearance mode
may be Item.PLAIN, Item.HYPERLINK or Item.BUTTON.
If the appearance mode is of type HYPERLINK or BUTTON, the default Command and the
ItemCommandListener must be set on the Item.

stringForm = new Form("StringField Modes");


stringForm.addCommand(exitCommand);
stringForm.setCommandListener(this);

StringItem plain = new StringItem("Plain", "Plain Text", Item.PLAIN);

StringItem hyperlink = new StringItem("Hyperlink", "http://www.sun.com",


Item.HYPERLINK);
hyperlink.setDefaultCommand(new Command("Set", Command.ITEM, 0));
hyperlink.setItemCommandListener(this);

StringItem button = new StringItem("Button", "Click me", Item.BUTTON);

Mobile Application Development

17

J.E.D.I.

button.setDefaultCommand(new Command("Set", Command.ITEM, 0));


button.setItemCommandListener(this);

stringForm.append(plain);
stringForm.append(hyperlink);
stringForm.append(button);

Figure 15: StringItem

3.10 Image Item


ImageItem is simply an Image that can be put on a component, like a Form.
The ImageItem accepts an item layout as parameter (see section on Item):
public ImageItem(
String label,
Image img,
int layout,
String altText)
Another constructor accepts an appearance mode which
Item.HYPERLINK or Item.BUTTON (see StringItem section):

can

be

Item.PLAIN,

public ImageItem(String label,


Image image,
int layout,

Mobile Application Development

18

J.E.D.I.

String altText,
int appearanceMode)

imageForm = new Form("ImageItem");


imageForm.addCommand(backCommand);
imageForm.setCommandListener(this);

try {
Image img = Image.createImage("/jedi.png");
ImageItem image =
new ImageItem("JEDI", img, Item.LAYOUT_CENTER, "jedi logo");
imageForm.append(image);
} catch (Exception e){e.printStackTrace();}
The file "jedi.png" is imported into the project by using the operating system's file manager
and putting the image file into the project directory under the subdirectory "src". The
project is then refreshed by right clicking the project name and selecting "Refresh Folders".

Mobile Application Development

19

J.E.D.I.

Figure 16: ImageItem

3.11 Text Field


A TextField is an Item where the user can encode input. Several mutually exclusive input
constraints can be set:

Mobile Application Development

20

J.E.D.I.

TextField.ANY
TextField.EMAILADDR
TextField.NUMERIC
TextField.PHONENUMBER
TextField.URL
TextField.DECIMAL

The input can also have the following modifiers:


TextField.PASSWORD
TextField.UNEDITABLE
TextField.SENSITIVE
TextField.NON_PREDICTIVE
TextField.INITIAL_CAPS_WORD
TextField.INITIAL_CAPS_SENTENCE
These modifiers can be set by using the bit-wise OR (|) operator (or toggled by using the
bit-wise XOR operator ^) on the input constraint. Consequently, modifiers can be derived
from the return value of getConstraints() the bit-wise AND operator (&).
Since modifiers are also returned by getConstraints(), the main input constraint can be
extracted by using the bit-wise AND operator with TextBox.CONSTAINT_MASK and the
return value of getConstaints().
getString() returns the contents of the TextField as a String value.

textForm = new Form("TextField Types");


textForm.addCommand(backCommand);
textForm.setCommandListener(this);

TextField ANY = new TextField("ANY", "", 64,

TextField.ANY);

TextField EMAILADDR =
new TextField("EMAILADDR", "", 64,

TextField.EMAILADDR);

TextField NUMERIC =
new TextField("NUMERIC", "", 64,

TextField.NUMERIC);

TextField PHONENUMBER =
new TextField("PHONENUMBER", "", 64,

TextField.PHONENUMBER);

TextField URL =
new TextField("URL", "", 64,

TextField.URL);

TextField DECIMAL =
new TextField("DECIMAL", "", 64,

TextField.DECIMAL);

textForm.append(ANY);
textForm.append(EMAILADDR);

Mobile Application Development

21

J.E.D.I.

textForm.append(NUMERIC);
textForm.append(PHONENUMBER);
textForm.append(URL);
textForm.append(DECIMAL);

Figure 17: TextField Items

3.12 Exercises
3.12.1 Dynamic List
Create a MIDlet that has an IMPLICIT List as its main Screen. Attach three Commands to
this List "Add Item", "Remove Item" and "Exit". The "Add Item" Command will prompt
the user for an list entry using a TextBox, then insert that item before the current selected
item on the list. "Remove Item" will remove the currently selected (getSelectedIndex) list
item. The "Exit" Command will exit the program.

Mobile Application Development

22

J.E.D.I.

Mobile Application Development

23