java 2 micro edition creating a user interface (part 2)ricci/ms/handsouts/4-j2me-gui-part2.pdf1 java...

27
1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items: Gauge, TextField, StringItem, ImageItem, DataField, ChoiceGroup Commands on items Responding to item’s changes Custom items Graphics in J2ME Responding to item traversal Summary of the Displayable hierarchy Summary of commands and events mamangement

Upload: others

Post on 09-Feb-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

1

Java 2 Micro EditionCreating a User Interface

(part 2)

F. Ricci

Contents

Forms

Items: Gauge, TextField, StringItem, ImageItem, DataField, ChoiceGroup

Commands on items

Responding to item’s changes

Custom items

Graphics in J2ME

Responding to item traversalSummary of the Displayable hierarchy

Summary of commands and events mamangement

Page 2: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

2

Advanced Interfaces with Forms

Form is a screen that can include a collection of user-interface controls called Item

Forms that don’t fit in the screen will automatically be made scrollable if neededOne way to create a Form is by calling

public Form(String title)

Form is essentially a collection of items, if you have all items defined you can pass them by calling:public Form(String title, Item[] items)

Form displays command and fires events (inherited from Displayable)

To set the focus on a particular item when a Form is shown use the metod setCurrentItem()

Managing Items

Items may be added and removed

The order of items is important

The following methods are available to manage items

public int append(Item item)

public int append(String str)

public int append(Image image)

public void set(int index, Item item)

public void insert(int index, Item item)

public void delete(int index)

public void deleteAll()

public int size() //number of items

public Item get(int index)

Page 3: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

3

Items - StringItem

StringItem represents a simple text label

There are two types of constructors:StringItem(String label, String text)

StringItem(String label, String text, int appearanceMode)

You can use null for StringItem label or value to indicate that it should not be shownUse getText() and setText() to access the string value

Items - StringItem

The appearance of both StringItem and ImageItemcan be controlled using appearance mode

The appearance mode allows the item to look like an URL link or a button - three appearance modes:

PLAIN: normal state

HYPERLINK: shows the item as URL

BUTTON: shows the item as a button

Remember, the appearance may look different on different device like almost everything else in the javax.microedition.lcdui package

Page 4: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

4

Form and Items

Form attempts to lay out items left-to-right in rows, stacking rows top-to-bottomThe Item class allows some control over the layout of individual items

All items have a string label (may be not visible)

Items can have commands (shown along with the commands in the form)

You can manage a command on an item using the addCommand() and removeCommand()

Note that the command type should be ITEM

Item Commands

public class MyHello extends MIDlet {private Form mform;private StringItem mItem;

public MyHello () {mform = new Form("Hello Form");mItem = new StringItem("hello: \n", "Hello my students!");mform.append(mItem);

mItem.addCommand(new Command("Exit from Item", Command.ITEM, 0));mItem.setItemCommandListener(new ItemCommandListener() {

public void commandAction(Command command, Item item) {notifyDestroyed();

}});

}

public void startApp() { Display.getDisplay(this).setCurrent(mform);

}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}}

code

Page 5: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

5

Form Layout – Item size

Item has fields related to layout control (where it should be placed in a form)

There is no Form layout

Item have a minimum size and preferred sizethat can be use to control how large an item appears in a form

Minimum size is computed by implementation and is not possible to change it serves in deciding how to layout a form

The preferred size can be computed by implementation or specified by you

If you specify a size that dimension will be used during layout (setPreferredSize(w,h))

Form Layout – Item Layout

Item class includes a layout directive accessed using getLayout() and setLayout()

Usually the layout value is a combination of LAYOUT_2(MIDP 2.0 rules) with a horizontal value and vertical valueHorizontal Values: LAYOUT_LEFT,LAYOUT_RIGHT, LAYOUT_CENTER

Vertical Values: LAYOUT_TOP, LAYOUT_BOTTOM, LAYOUT_VCENTER

Request a new-line after/before the item: LAYOUT_NEWLINE_AFTER, LAYOUT_NEWLINE_BEFORE

Example

int prefLayout = Item.LAYOUT_2 | Item.LAYOUT_LEFT| Item.LAYOUT_NEWLINE_AFTER;

mVideoItem.setLayout(prefLayout);

Page 6: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

6

Items – TextField

TextField represent an editable stringTextField(String label, String text, int maxSize, int constraints)Ex: mform.append(new TextField("Phone", "+390471555888", 50, TextField.PHONENUMBER));TextFields can limit input using the following

ANY any type of inputNUMERIC restrict input to numbersDECIMAL allows numbers with fractional partsPHONENUMBER requires a telephone numberEMAILADDR input must be an e-mail addressURL input must be an URL

The input constraints are the same as TextBox and can be combined with the other constraints using the OR operator (see TextBox constants)For an initial empty TextField pass null for the textparameter

Items - ImageItem

Forms can contain images, which are represented by an instance of ImageItem

To create an ImageItem just supply the Image to be displayed, the label, layout and alternate text

Example:waitImage = Image.createImage("/wait.png");

mColorSquare = new ImageItem(null, waitImage,ImageItem.LAYOUT_DEFAULT, "coloredsquare");

Layout is controlled by the constants:LAYOUT_DEFAULT, LAYOUT_CENTER, LAYOUT_LEFT, LAYOUT_RIGHT

LAYOUT_NEWLINE_BEFORE, LAYOUT_NEWLINE_AFTER

ImageItem support appearance modes just like StringItem(using the appropriate constructor)

Page 7: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

7

Items - DateField

DateField is an useful mechanism by which users can enter dates, times or bothTo create a DateField specify a label and a mode:

DATE display an editable date

TIME displays an editable time

DATE_TIME displays both date and time

There are two constructor the first uses default TimeZoneusing the second you have to specify TimeZoneDateField(String label, int mode)

DateField(String label, int mode, TimeZone timeZone)

To get or set the Date represented by the DateField use the Following methods:

Public Date getDate()

Public void setDate(Date date)

Items - Gauge

Gauge represents an integer value

The value of a Gauge instance can be retrieved or modified with the getValue() and setValue()-this value runs from 0 to a maximum value

Maximum value can be retrieved and modified with the getMaxValue() and setMaxValue()

In an interactive gauge the user can modify the valueTo create a Gauge use the following constructor

public Gauge(String label, booleaninteractive, int maxValue, int initialValue)

Page 8: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

8

There are three varieties of noninteractive gauges than can be useful as progress indicators:

With definite maximum value the application can increase and decrease its valueWith indefinite maximum value

Incremental: your application forces advance one step or set to idleContinuous: it advances continuously unless is idle

The value of a gauge with indefinite maximum can be set toGauge.INCREMENTAL_UPDATING = advances by one stepGauge.INCREMENTAL_IDLE = changes color to show that it is idleGauge.CONTINUOUS_RUNNING = the gauge is animatedGauge.CONTINUOS_IDLE = changes color to show that it is idle

Non Interactive gauges

GaugeMIDlet – source (I)

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

public class GaugeMIDletextends MIDletimplements CommandListener {

private Display mDisplay;

private Form mGaugeForm;private Command mUpdateCommand, mIdleCommand;

private Gauge mInteractiveGauge;private Gauge mIncrementalGauge;private Gauge mContinuousGauge;

code

Page 9: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

9

GaugeMIDlet – source (II)

public GaugeMIDlet() {

mGaugeForm = new Form("Gauges");

mInteractiveGauge = new Gauge("Interactive", true, 5, 2);

mInteractiveGauge.setLayout(Item.LAYOUT_2);

mGaugeForm.append(mInteractiveGauge);

mContinuousGauge = new Gauge("Non-I continuous", false,

Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);

mContinuousGauge.setLayout(Item.LAYOUT_2);

mGaugeForm.append(mContinuousGauge);

mIncrementalGauge = new Gauge("Non-I incremental", false,

Gauge.INDEFINITE, Gauge.INCREMENTAL_UPDATING);

mIncrementalGauge.setLayout(Item.LAYOUT_2);

mGaugeForm.append(mIncrementalGauge);

mUpdateCommand = new Command("Update", Command.SCREEN, 0);

mIdleCommand = new Command("Idle", Command.SCREEN, 0);

Command exitCommand = new Command("Exit", Command.EXIT, 0);

mGaugeForm.addCommand(mUpdateCommand);

mGaugeForm.addCommand(mIdleCommand);

mGaugeForm.addCommand(exitCommand);

mGaugeForm.setCommandListener(this);

}

GaugeMIDlet – source (III)

public void startApp() {if (mDisplay == null) mDisplay = Display.getDisplay(this);mDisplay.setCurrent(mGaugeForm);

}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {if (c.getCommandType() == Command.EXIT)notifyDestroyed();

else if (c == mUpdateCommand) {mContinuousGauge.setValue(Gauge.CONTINUOUS_RUNNING);mIncrementalGauge.setValue(Gauge.INCREMENTAL_UPDATING);

}else if (c == mIdleCommand) {mContinuousGauge.setValue(Gauge.CONTINUOUS_IDLE);mIncrementalGauge.setValue(Gauge.INCREMENTAL_IDLE);

}}

}

Page 10: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

10

Items - ChoiceGroup

ChoiceGroup offers a list of choices

Is similar to List and implements the same Choice interface - the constructors are:ChoiceGroup(String label, int choiceType)

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

choiceType can be EXCLUSIVE, MULTIPLE or POPUP (there is no IMPLICT as in List)

Responding to Item Changes

Most items in a Form fire events when the user changes them

The application can listen for these events by registering an ItemStateListener with the Form using the following method:public void setItemStateListener(ItemStateListener

iListener)

ItemStateListener is an interface with a single method:public void itemStateChanged(Item item)

That method is called every time an item in a Form is changed

In the following example there is a Form with two items, an interactive Gauge and a StringItem

As you adjust the Gauge, its value is reflected in the StringItem using the ItemStateListener mechanism

Page 11: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

11

GaugeTracker example (I)

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

public class GaugeTrackerextends MIDletimplements ItemStateListener, CommandListener {

private Gauge mGauge;private StringItem mStringItem;

public GaugeTracker() {int initialValue = 3;mGauge = new Gauge("GaugeTitle", true, 5, initialValue);mStringItem = new StringItem(null, "[value]");itemStateChanged(mGauge);

}

public void itemStateChanged(Item item) {if (item == mGauge)

mStringItem.setText("Value = " + mGauge.getValue());}

public void commandAction(Command c, Displayable s) {if (c.getCommandType() == Command.EXIT)

notifyDestroyed();}

code

GaugeTracker example (II)

public void startApp() {Form form = new Form("GaugeTracker");form.addCommand(new Command("Exit", Command.EXIT, 0));form.setCommandListener(this);// Now add the selected items.form.append(mGauge);form.append(mStringItem);form.setItemStateListener(this);

Display.getDisplay(this).setCurrent(form);}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}}

Page 12: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

12

ItemStateChanged

public void itemStateChanged(Item item)

Called when internal state of an Item has been changed by the user

This happens when the user:

changes the set of selected values in a ChoiceGroup;

adjusts the value of an interactive Gauge;

enters or modifies the value in a TextField;

enters a new date or time in a DateField;

CustomItem

A CustomItem is a customizable item used to introduce new visual and interactive elements into Forms To implement a CustomItem, define a subclass of CustomItem (abstract class) by implementing five abstract methodsThe first four have to do with the size of the item’s content area:protected int getPrefContentWidth(int height)protected int getPrefContentHeight(int width) protected int getMinContWidth()protected int getMinContentHeight()

The total area of the custom item includes a label and perhaps bordersThe CustomItem subclass is only responsible for the content area

Page 13: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

13

CustomItem

The fifth method that must be defined is the paint() which the implementation calls to render the itemprotected void paint(Graphics g, int w, int h)

The Graphics object can be used to draw lines, shapes, text, and images on the content area of the itemThe w and h indicates the current width and height of the content areaThe implementation will call the paint method when the MIDlet set the CustomItem as the current Displayable

Coordinate System

The coordinate system represents locations between pixels, not the pixels themselvesTherefore, the first pixel in the upper left corner of the display lies in the square bounded by coordinates (0,0) , (1,0) , (0,1) , (1,1)

Since coordinate grid lines lie between pixels, fill operations affect pixels that lie entirely withinthe region bounded by the coordinates of the operation.

(0,0)

(0,1)

(1,0) (2,0)

(1,1) (2,1)

PIXEL

x

y

Page 14: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

14

Rectangles and Triangles

The operation g.fillRect(0, 0, 3, 2)

Will fill exactly 6 pixels

The operation g.fillTriangle(0, 0, 0, 2, 2,2)

(0,0)

(0,1)

(1,0) (2,0)

(1,1) (2,1)

(3,0)

(3,1)

(0,2) (1,2) (2,2) (3,2)

(0,0)

(0,1) (1,1)

(0,2) (1,2) (2,2)

Will fill only one pixel

Lines

For the SOLID stroke style, drawing operations are performed with a one-pixel wide pen that fills the pixel immediately below and to the right of the specified coordinate

Drawn lines touch pixels at both endpoints

Thus, the operation g.drawLine(0, 0, 0, 0); will paint one pixel

And g.drawLine(0, 0, 1, 0); two pixels.

(0,0)

(0,1)

(1,0) (2,0)

(1,1) (2,1)

(3,0)

(3,1)

(0,0)

(0,1)

(1,0) (2,0)

(1,1) (2,1)

(3,0)

(3,1)

Page 15: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

15

SimpleItemMIDlet

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

public class SimpleItemMIDletextends MIDletimplements CommandListener {

public void startApp() {Form form = new Form("SimpleItemMIDlet");form.append(new SimpleItem("SimpleItem"));

Command c = new Command("Exit", Command.EXIT, 0);form.addCommand(c);form.setCommandListener(this);

Display.getDisplay(this).setCurrent(form);}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {if (c.getCommandType() == Command.EXIT)

notifyDestroyed();}

}

code

SimpleItem - example

import javax.microedition.lcdui.*;public class SimpleItem

extends CustomItem {public SimpleItem(String title) { super(title); }public int getMinContentWidth() { return 100; }public int getMinContentHeight() { return 60; }

public int getPrefContentWidth(int width) {return getMinContentWidth();

}public int getPrefContentHeight(int height) {return getMinContentHeight();

}public void paint(Graphics g, int w, int h) {g.drawRect(0, 0, w - 1, h - 1);g.setColor(0x000000ff);int offset = 0;for (int y = 4; y < h; y += 12) {offset = (offset + 12) % 24;for (int x = 4; x < w; x += 24) {g.fillTriangle(x + offset, y,

x + offset - 3, y + 6,x + offset + 3, y + 6);

}}}}

code

Page 16: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

16

Triangles

public void paint(Graphics g, int w, int h) {g.drawRect(0, 0, w - 1, h - 1);g.setColor(0x000000ff);int offset = 0;for (int y = 4; y < h; y += 12) {

offset = (offset + 12) % 24;for (int x = 4; x < w; x += 24) {

g.fillTriangle(x + offset, y,x + offset - 3, y + 6,x + offset + 3, y + 6);

}}

4

16

28

0 12 24

40

52

60

CustomItem Painting (I)

A CustomItem is drawn on the screen in its paint()methodThis method is passed a Graphics object that

Represents the drawing surface of the CustomItem’scontent area

Provides numerous methods for drawing shapes, images and text

The paint() method is called by the implementation whenever it needs to show your custom item on the screen

If something needs to change in your custom item’s appearance you can request a refresh by calling the repaint() method

If you would refresh only a part of the item just callrepaint(int x, int y, int width, int height) to describe the rectangular region to be drawn.

Page 17: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

17

CustomItem Painting (II)

There are two methods that can help you make your item’s appearance consistent with the device’s look and feelpublic int getColor(int colorSpecifier) method, of the Displayclass, returns an int representing the color of the Display

colorSpecifier must be one of the following constants (of Display)Display.COLOR_BACKGROUND, Display.COLOR_BORDER, Display.COLOR_FOREGROUND, Display.COLOR_HIGHLIGHTED_BACKGROUND, Display.COLOR_HIGHLIGHTED_BORDER, Display.COLOR_HIGHLIGHTED_FOREGROUND

getFont() static method of Font returns an appropriate Font object that you can use for drawing text, passing a font specifier const

Font.FONT_STATIC_TEXT, Font.FONT_INPUT_TEXTExample:public void paint(Graphics g) {

Font f = Font.getFont(Font.FONT_INPUT_TEXT);

g.setFont(f);

// draw text … }

Showing, Hiding, and Sizing

When a CustomItem is made visible, its showNotify()methods is called by the MIDP implementation (the default implementation do nothing)You can expect a subsequentially calls to paint() to render the itemSimilarly the hideNotify() is called when the item is no longer visible (e.g. when the midlet is terminated - the default implementation do nothing)The size of your custom item may be changed by the implementation in this case the item’s sizeChanged()method is called with the new width and height of the content areaIf the item needs to be a different size it should call the invalidate() method, which signals the implementation that it need to layout the Form

Page 18: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

18

Handling Events

A CustomItem can respond to keystrokes and pointer events by overriding any or all of the following methodsprotected void keyPressed(int keyCode)protected void keyReleased(int keyCode)protected void keyRepeated(int keyCode)protected void pointerPressed(int x, int y)protected void pointerReleased(int x, int y)protected void pointerDragged(int x, int y)

These method are called in response to the user’s actionsThe keyCode parameter will be one of the constant defined in the Canvas class (KEY_NUM0,…,KEY_NUM9, …)The pointer callback supply the location of the pointerMany phones will not support pointer events, to find out the capabilities of the device at runtime, use the getInteractionModes() method, this will return a bitmask of the available interaction modes (static fields of CustomItem): KEY_PRESS, KEY_RELEASE, KEY_REPEAT, POINTER_PRESS, POINTER_RELEASE, POINTER_DRAG, TRAVERSE_HORIZONTAL, TRAVERSE_VERTICAL.

Item (Internal) Traversal

Form Traversal

Internal Item Traversal

Two methods signal traversal events. The first traverse(),

Is called the first time the user traverses into the item.

By default this method returns false indicating that the Item does not support

internal traversalThe second traverseOut()

when the user leaves the item.

Page 19: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

19

Item Traversal

Form support a concept of focus, where one item in the form is currently selected

Traversal refers to the user being able to shift focus from one item to another

In most cases the MIDP implementation handles the details of Form traversal

With default implementation provided in CustomItem you don’t have to think about traversal in many cases

But if you want to do something special when an item is traversed internally, then …

Item Traversal

The traverse() method is called when focus first comes to your itemIf this method returns true, then traverse() will be repeatedly called until it will return false (exit from an item)If you do write a custom item that supports internal traversal, you need to pay attention to the arguments passed to traverse() and you need to return true to indicate that your item support internal traversals (default is false)Boolean traverse(int dir, int viewportWidth, int

viewportHeight, int[] visRect_inout);

dir indicates the direction: Canvas.UP, Canvas.DOWN, Canvas.LEFT, Canvas.RIGHT, CustomItem.NONE

viewPortWidth and viewPortHeight: the size available for items in the Form containing this custom itemvisRect_inout: is an integer array with four elements and describes the region of the custom item’s visible content area (should contain the bound of the selected choice in the item)

Page 20: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

20

StationSign

An Example – StationSign

Implements a simple scrolling list of string choices. Pointer events and key events cause the current selection to move to the next choiceThe scrolling is animatedStationSign is a RunnableA separate thread is created in the constructor and used to call the run() methodIf there’s a difference between the current display state of the item and the current selection, run() reconciles the two by scrollingConforms to the device’s look and feel by using the font for static text and colors returned from Display’s getColor()methodDoes not implement internal traversalUses traverse() and traverseOut() methods to recognize focus and paint using highlight colors.

Page 21: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

21

StationSign MIDlet

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

public class StationSignMIDletextends MIDletimplements CommandListener {

public void startApp() {Display display = Display.getDisplay(this);

//System.out.println(System.getProperty("microedition.encoding"));Form form = new Form("StationSignMIDlet");form.append(new StringItem("StringItem: ", "this is the first item"));StationSign ss = new StationSign("Destination", display);ss.add("Albuquerque");ss.add("Savannah");ss.add("Pocatello");ss.add("Des Moines");form.append(ss);form.append(new StringItem("StringItem: ", "this is item two"));

Command c = new Command("Exit", Command.EXIT, 0);form.addCommand(c);form.setCommandListener(this);

display.setCurrent(form);}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {if (c.getCommandType() == Command.EXIT)notifyDestroyed();

}}

code

StationSign code I– constructor

import java.util.Vector;

import javax.microedition.lcdui.*;

public class StationSignextends CustomItemimplements Runnable {

private Vector mValues;private int mSelection;private boolean mTrucking;

private Display mDisplay;private Font mFont;private int mVisibleIndexTimesTen;private boolean mFocus;

public StationSign(String title, Display display) {super(title);mDisplay = display;mValues = new Vector();mSelection = 0;mTrucking = true;mFont = Font.getFont(Font.FONT_STATIC_TEXT);mVisibleIndexTimesTen = mSelection * 10;

Thread t = new Thread(this);t.start();

}

code

Page 22: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

22

StationSign – code (II)

public void add(String value) {if (value == null) return;mValues.addElement(value);

}

public void remove(String value) {if (value == null) return;mValues.removeElement(value);

}

public String getSelection() {if (mValues.size() == 0) return "";return (String)mValues.elementAt(mSelection);

}

public void flip() {mSelection++;if (mSelection >= mValues.size()) mSelection = 0;

}

public void dispose() {mTrucking = false;

}

StationSign – code (III)

// Runnable interface.

public void run() {while (mTrucking) {int target = mSelection * 10;if (mVisibleIndexTimesTen != target) {mVisibleIndexTimesTen++;if (mVisibleIndexTimesTen >= mValues.size() * 10)mVisibleIndexTimesTen = 0;

repaint();}try { Thread.sleep(50); }catch (InterruptedException ie) {}

}}

Page 23: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

23

StationSign – code (IV)

// CustomItem abstract methods.

public int getMinContentWidth() {// Loop through the values. Find the maximum width.int maxWidth = 0;for (int i = 0; i < mValues.size(); i++) {

String value = (String)mValues.elementAt(i);int width = mFont.stringWidth(value);maxWidth = Math.max(maxWidth, width);

}// Don't forget about the title, although we don't// really know what font is used for that.int width = mFont.stringWidth(getLabel()) + 20;maxWidth = Math.max(maxWidth, width);return maxWidth;

}

public int getMinContentHeight() {return mFont.getHeight();

}

public int getPrefContentWidth(int width) {return getMinContentWidth();

}

public int getPrefContentHeight(int height) {return getMinContentHeight();

}

StationSign – code (V) – paint

public void paint(Graphics g, int w, int h) {int fraction = mVisibleIndexTimesTen % 10;int visibleIndex = (mVisibleIndexTimesTen - fraction) / 10;String value = (String)mValues.elementAt(visibleIndex);

g.setFont(mFont);int bc = mDisplay.getColor(Display.COLOR_BACKGROUND);int fc = mDisplay.getColor(Display.COLOR_FOREGROUND);if (mFocus == true) {bc = mDisplay.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND);fc = mDisplay.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND);

}g.setColor(bc);g.fillRect(0, 0, w, h);g.setColor(fc);

// Simple case: visibleIndex is aligned on a single item.if (fraction == 0) {g.drawString(value, 0, 0, Graphics.TOP | Graphics.LEFT);return;

}

Page 24: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

24

StationSign – code (V) – paint

// Complicated case: show two items and a line.int lineHeight = mFont.getHeight();int divider = lineHeight - lineHeight * fraction / 10;

// Draw the piece of the visible value.g.drawString(value, 0, divider - lineHeight,

Graphics.TOP | Graphics.LEFT);// Now get the next value.visibleIndex = (visibleIndex + 1) % mValues.size();value = (String)mValues.elementAt(visibleIndex);

// Draw the line.g.setStrokeStyle(Graphics.DOTTED);g.drawLine(0, divider, w, divider);

g.drawString(value, 0, divider,Graphics.TOP | Graphics.LEFT);

}

StationSign – code (VII)

// CustomItem methods.

protected void keyPressed(int keyCode) { flip (); }

protected void pointerPressed(int x, int y) { flip(); }

protected boolean traverse(int dir,int viewportWidth, int viewportHeight,int[] visRect_inout) {

mFocus = true;repaint();return false;

}

protected void traverseOut() {mFocus = false;repaint();

}}

Page 25: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

25

Summary on GUI and MIDlet

Displayable has two sub-types: Canvas and ScreenScreen has four sub-types:

TextBox: input of textList: selecting one option among a listAlert: pop up a message to the userForm: aggregates simple GUI Item

Item has eight sub-types: StringItem has three appearances: PLAIN, HYPERLINK,BUTTONTextField is like a TextBoxImageItem to display imagesDateField to input a dateGauge to show and input an integer in a rangeChoiceGroup similar to ListSpacer to set some space between items CustomItem to do whatever you like!

Summary on Commands

A Command c can be added to any Displayable Screen d

d.addCommand(c);

The Command is managed by registering aCommandListener cl to the Displayable

d.setCommandListener(cl);

The CommandListener must implement the method

commandAction(Command c, Dysplayable s)

A Command c can be added to an Item i (i.addCommand(c);)

It is managed by registering an ItemCommandListener iclto the Item i:

i.setItemCommandListener(icl);

An ItemCommandListener must implement:

commandAction(Command command, Item item)

Page 26: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

26

Summary on Events on Items

When an Item is changed, the method

public void itemStateChanged(Item item)

of the ItemStateListern object registered to the item is calledTo register a ItemStateListener use the method:

public void setItemStateListener(ItemStateListeneriListener)

Events on CustomItem

A CustomItem can respond to many eventsprotected void keyPressed(int keyCode)

protected void keyReleased(int keyCode)

protected void keyRepeated(int keyCode)

protected void pointerPressed(int x, int y)

protected void pointerReleased(int x, int y)

protected void pointerDragged(int x, int y)

Including traversalBoolean traverse(int dir, int viewportWidth, int viewportHeight, int[] visRect_inout)

protected void traverseOut()

Page 27: Java 2 Micro Edition Creating a User Interface (part 2)ricci/MS/Handsouts/4-J2ME-GUI-part2.pdf1 Java 2 Micro Edition Creating a User Interface (part 2) F. Ricci Contents Forms Items:

27

Exercise on Forms

Write a form to collect information about the user using different item types (TextField, DateField, ChoiceGroup)

Name, Family Name, City, State, PhoneNumber, email, birthdate, Gender (ChoiceGroup.EXCLUSIVE), favorite color (ChoiceGroup.POPUP), favorite activity(ChoiceGroup.MULTIPLE)

Use the collected information and print them on the screen with a layout like a letter or SMS.