Java/J2ME/Event Command
Содержание
- 1 Accessing Commands
- 2 A first MIDlet with simple text and a few commands.
- 3 An example MIDlet with simple Hello text and an Exit command
- 4 Api concepts Refer to the startApp pauseApp, and destroyApp
- 5 A quick sample of graphics, commands, and event handling.
- 6 Capture Item Events
- 7 Commander
- 8 Commands, Items, and Event Processing
- 9 Many Commands
- 10 Mapping Commands
- 11 Online Help
- 12 Simple Command Demo
- 13 Various Event
Accessing Commands
/*--------------------------------------------------
* AccessingCommands.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class AccessingCommands extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // A Form
private Command cmExit; // A Command to exit the MIDlet
public AccessingCommands()
{
display = Display.getDisplay(this);
cmExit = new Command("Exit", Command.EXIT, 1);
fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.setCommandListener(this);
}
// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}
// A required method
public void pauseApp()
{ }
// A required method
public void destroyApp(boolean unconditional)
{ }
// Check to see if our Exit command was selected
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}
A first MIDlet with simple text and a few commands.
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
// A first MIDlet with simple text and a few commands.
public class FirstMIDlet extends MIDlet
implements CommandListener {
//The exit, info, and buy commands
private Command exitCommand;
private Command infoCommand;
private Command buyCommand;
//The display for this MIDlet
private Display display;
public FirstMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.SCREEN, 1);
infoCommand = new Command("Info",Command.SCREEN, 2);
buyCommand = new Command("Buy", Command.SCREEN, 2);
}
// Start the MIDlet by creating the TextBox and
// associating the exit command and listener.
public void startApp() {
TextBox t = new TextBox("FirstMIDlet",
"Welcome to MIDP Programming", 256, 0);
t.addCommand(exitCommand);
t.addCommand(infoCommand);
t.addCommand(buyCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
// Pause is a no-op because there are no background
// activities or record stores to be closed.
public void pauseApp() { }
// Destroy must cleanup everything not handled
// by the garbage collector.
// In this case there is nothing to cleanup.
public void destroyApp(boolean unconditional) { }
// Respond to commands. Here we are only implementing
// the exit command. In the exit command, cleanup and
// notify that the MIDlet has been destroyed.
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
An example MIDlet with simple Hello text and an Exit command
/*
*
* Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* An example MIDlet with simple "Hello" text and an Exit command.
* Refer to the startApp, pauseApp, and destroyApp
* methods so see how each handles the requested transition.
*/
public class HelloCommandMIDlet extends MIDlet implements CommandListener {
private Command exitCommand; // The exit command
private Command okCommand; // The exit command
private Command cancelCommand; // The exit command
private Command nextCommand; // The exit command
private Command backCommand; // The exit command
private Display display; // The display for this MIDlet
public HelloCommandMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 2);
}
/**
* Start up the Hello MIDlet by creating the TextBox and associating
* the exit command and listener.
*/
public void startApp() {
TextBox t = new TextBox("Hello", "Hello World!", 256, 0);
t.addCommand(exitCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
/**
* Pause is a no-op since there are no background activities or
* record stores that need to be closed.
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything not handled by the garbage collector.
* In this case there is nothing to cleanup.
*/
public void destroyApp(boolean unconditional) {
}
/*
* Respond to commands, including exit
* On the exit command, cleanup and notify that the MIDlet has been destroyed.
*/
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
Api concepts Refer to the startApp pauseApp, and destroyApp
/*
* AdvanceCommands.java
* Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* Author: Srikanth Raju
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
/**
* An MIDlet that illustrates more MIDP UI Api concepts Refer to the startApp,
* pauseApp, and destroyApp methods so see how each handles the requested
* transition.
*/
public class AdvanceCommands extends MIDlet implements CommandListener {
private Command exitCommand; // The exit command
private Command nextCommand; // next command
private Command backCommand; // back command
private TextBox t1;
private TextBox t;
private Display display; // The display for this MIDlet
public AdvanceCommands() {
display = Display.getDisplay(this);
nextCommand = new Command("Next", Command.SCREEN, 1);
exitCommand = new Command("Quit", Command.SCREEN, 2);
backCommand = new Command("Back", Command.BACK, 2);
}
/**
* Start up the Hello MIDlet by creating the TextBox and associating the
* exit command and listener.
*/
public void startApp() {
t = new TextBox("Hello MIDlet", "Test string", 256, 0);
t.addCommand(nextCommand);
t.addCommand(exitCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
/**
* Pause is a no-op since there are no background activities or record
* stores that need to be closed.
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything not handled by the garbage collector. In
* this case there is nothing to cleanup.
*/
public void destroyApp(boolean unconditional) {
}
/*
* Respond to commands, including exit On the exit command, cleanup and
* notify that the MIDlet has been destroyed.
*/
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
if (c == nextCommand) {
t1 = new TextBox("2nd TextBox", "2nd TextBox", 256, 0);
t1.addCommand(backCommand);
t1.addCommand(exitCommand);
t1.setCommandListener(this);
display.setCurrent(t1);
}
if (c == backCommand) {
display.setCurrent(t);
}
}
}
A quick sample of graphics, commands, and event handling.
/*
* @(#)Sample.java 1.9 01/06/08
* Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/*
* A quick sample of graphics, commands, and event handling.
*/
public class SampleCanvasMIDlet extends MIDlet implements CommandListener {
Display display;
Command exitCommand;
Command backCommand;
Command okCommand;
SampleCanvas sample; // Instance of sample canvas
List itemMenu;
List exclusiveList;
List multipleList;
TextBox textbox;
Ticker ticker;
Alert alert;
Form form;
StringItem stringItem;
ImageItem imageItem;
Image image;
TextField textItem;
ChoiceGroup choiceItem;
DateField dateItem;
Gauge gaugeItem;
public SampleCanvasMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 1);
backCommand = new Command("Back", Command.BACK, 2);
okCommand = new Command("OK", Command.OK, 3);
ticker = new Ticker("Select an item to display");
itemMenu = new List(null, Choice.IMPLICIT);
itemMenu.append("Canvas", null);
itemMenu.append("Form", null);
itemMenu.append("Alert", null);
itemMenu.append("TextBox", null);
itemMenu.append("Exclusive List", null);
itemMenu.append("Multiple Choice", null);
itemMenu.setCommandListener(this);
itemMenu.addCommand(exitCommand);
itemMenu.setTicker(ticker);
display.setCurrent(itemMenu);
}
public void startApp () {
}
public void destroyApp (boolean unconditional) {
}
public void pauseApp () {
}
public void commandAction(Command c, Displayable s) {
if (c == backCommand) {
display.setCurrent(itemMenu);
} else if (s == itemMenu) {
if (c == List.SELECT_COMMAND) {
// Handle the item sected to be displayed
int i = itemMenu.getSelectedIndex();
switch (i) {
case 0: // Show Sample canvas
display.setCurrent(getCanvas());
break;
case 1: // Show the form
display.setCurrent(getForm());
break;
case 2: // Show an alert
display.setCurrent(getAlert("Warning",
"This window will dismiss in two seconds."));
break;
case 3: // Show TextBox
display.setCurrent(getTextBox());
break;
case 4: // Show Exclusive list
display.setCurrent(getExclusiveList());
break;
case 5: // Show Multiple List
display.setCurrent(getMultipleList());
break;
}
} else if (c == exitCommand) {
notifyDestroyed();
}
} else if (s == exclusiveList) {
int i = exclusiveList.getSelectedIndex();
String value = exclusiveList.getString(i);
alert = getAlert("Border selected:", value);
display.setCurrent(alert, itemMenu);
} else if (s == multipleList) {
StringBuffer b = new StringBuffer();
for (int i = 0; i <= 2; i++) {
if (multipleList.isSelected(i)) {
b.append(multipleList.getString(i));
b.append("\n");
}
}
alert = getAlert("Colors selected:", b.toString());
display.setCurrent(alert, itemMenu);
} else if (s == textbox) {
String value = textbox.getString();
alert = getAlert("Text Entered:", value);
display.setCurrent(alert, itemMenu);
} else if (s == form) {
alert = getAlert("Image options saved", "");
display.setCurrent(alert, itemMenu);
}
}
SampleCanvas getCanvas() {
if (sample == null) {
sample = new SampleCanvas();
sample.addCommand(backCommand);
sample.setCommandListener(this);
}
return sample;
}
List getExclusiveList() {
if (exclusiveList == null) {
exclusiveList = new List("Border Style", Choice.EXCLUSIVE);
exclusiveList.append("None", null);
exclusiveList.append("Plain", null);
exclusiveList.append("Fancy", null);
exclusiveList.addCommand(backCommand);
exclusiveList.addCommand(okCommand);
exclusiveList.setCommandListener(this);
}
return exclusiveList;
}
List getMultipleList() {
if (multipleList == null) {
multipleList = new List("Colors to mix", Choice.MULTIPLE);
multipleList.append("Red", null);
multipleList.append("Green", null);
multipleList.append("Blue", null);
multipleList.addCommand(backCommand);
multipleList.addCommand(okCommand);
multipleList.setCommandListener(this);
}
return multipleList;
}
TextBox getTextBox() {
if (textbox == null) {
textbox = new TextBox("Enter a phone number","", 40,
TextField.PHONENUMBER);
textbox.addCommand(backCommand);
textbox.addCommand(okCommand);
textbox.setCommandListener(this);
}
return textbox;
}
Alert getAlert(String title, String contents) {
if (alert == null) {
alert = new Alert(title);
alert.setType(AlertType.WARNING);
alert.setTimeout(2000);
alert.setString(contents);
} else {
alert.setTitle(title);
alert.setString(contents);
}
return alert;
}
Form getForm() {
if (form == null) {
form = new Form("Options");
try {
image = Image.createImage("/images/PhotoAlbum.png");
imageItem = new ImageItem("Preview:", image,
ImageItem.LAYOUT_NEWLINE_BEFORE, "Mountain");
form.append(imageItem);
} catch (java.io.IOException ex) {
}
textItem = new TextField("Title:", "Mountain", 32,
TextField.ANY);
form.append(textItem);
dateItem = new DateField("Date:", DateField.DATE);
dateItem.setDate(new java.util.Date());
form.append(dateItem);
choiceItem = new ChoiceGroup("Size:", Choice.EXCLUSIVE);
choiceItem.append("Small", null);
choiceItem.append("Large", null);
form.append(choiceItem);
gaugeItem = new Gauge("Speed:", true, 10, 5);
form.append(gaugeItem);
form.addCommand(backCommand);
form.addCommand(okCommand);
form.setCommandListener(this);
}
return form;
}
}
class SampleCanvas extends Canvas {
int x, y; // Location of cross hairs
String event = ""; // Last key event type
int keyCode; // Last keyCode pressed
Font font; // Font used for drawing text
int fh; // height of the font
int w, h; // width and height of the canvas
int titleHeight; // Height of the title
int pieSize; // Size of the Pie chart used for width and height
int barSize; // Size of the Bar chart used for width and height
int eventHeight; // Size of the event region
int pad; // Padding used between items
SampleCanvas() {
w = getWidth();
h = getHeight();
font = Font.getFont(Font.FACE_SYSTEM,
Font.STYLE_PLAIN, Font.SIZE_SMALL);
fh = font.getHeight();
/* Compute the sizes of the bar and pie charts
* It should use all the space except for the title
* and event regions.
* Don"t let the charts get too small
*/
pad = 2;
titleHeight = fh + pad * 2;
eventHeight = fh * 3;
barSize = h - (titleHeight + pad) - (eventHeight + pad);
if (barSize < 20) // Don"t let them get too small
barSize = 20;
if (barSize > (w - pad) / 2) // Shrink to 1/2 width
barSize = (w - pad) / 2;
pieSize = barSize;
}
protected void keyPressed(int key) {
keyCode = key;
event = "Pressed";
handleActions(key);
repaint();
}
protected void keyRepeated(int key) {
keyCode = key;
event = "Repeated";
handleActions(key);
repaint();
}
protected void keyReleased(int key) {
keyCode = key;
event = "Released";
repaint();
}
protected void pointerPressed(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Pressed";
repaint();
}
protected void pointerReleased(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Released";
repaint();
}
protected void pointerDragged(int x, int y) {
this.x = x;
this.y = y;
keyCode = 0;
event = "Dragged";
}
void handleActions(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case LEFT:
x -= 1;
break;
case RIGHT:
x += 1;
break;
case UP:
y -= 1;
break;
case DOWN:
y += 1;
break;
}
}
protected void paint(Graphics g) {
g.setFont(font);
g.setGrayScale(255);
g.fillRect(0, 0, w, h);
x = (x < 0) ? w - 1 : x;
y = (y < 0) ? h - 1 : y;
x = x % w;
y = y % h;
// Draw Fill and outline for background of title Text
int swidth = pad * 2 + font.stringWidth("Pie and Bar Samples");
int title_x = (w - swidth)/2;
g.setGrayScale(128);
g.fillRoundRect(title_x, 0, swidth, fh, 5, 5);
g.setGrayScale(0);
g.drawRoundRect(title_x, 0, swidth, fh, 5, 5);
// Sample Text
g.setColor(0, 0, 0);
g.drawString("Pie and Bar Samples",
title_x + pad, pad, Graphics.TOP|Graphics.LEFT);
// Translate to below title text
g.translate(0, titleHeight + pad);
/*
* Draw pie chart on the left side
* using the barSize for width and height
*/
g.setColor(255, 0, 0);
g.fillArc(0, 0, pieSize, pieSize, 45, 270);
g.setColor(0, 255, 0);
g.fillArc(0, 0, pieSize, pieSize, 0, 45);
g.setColor(0, 0, 255);
g.fillArc(0, 0, pieSize, pieSize, 0, -45);
g.setColor(0);
g.drawArc(0, 0, pieSize, pieSize, 0, 360);
// Draw Bar chart on right side of the display
// scale the values to the pieSize maximum value
int yorig = barSize;
int h1 = barSize / 3, h2 = barSize / 2, h3 = barSize;
int avg = (h1 + h2 + h3) / 3;
// Move over to draw Bar chart
g.translate((w + pad) / 2, 0);
int bw = pieSize / 7;
if (bw < 2)
bw = 2;
g.setColor(255, 0, 0);
g.fillRect(bw*1, yorig-h1, bw+1, h1);
g.setColor(0, 255, 0);
g.fillRect(bw*3, yorig-h2, bw+1, h2);
g.setColor(0, 0, 255);
g.fillRect(bw*5, yorig-h3, bw+1, h3);
g.setColor(0);
g.drawRect(bw*1, yorig-h1, bw, h1);
g.drawRect(bw*3, yorig-h2, bw, h2);
g.drawRect(bw*5, yorig-h3, bw, h3);
// Draw axis for bar chart.
g.setGrayScale(0);
g.drawLine(0, 0, 0, yorig);
g.drawLine(0, yorig, barSize, yorig);
g.setStrokeStyle(Graphics.DOTTED);
g.drawLine(0, yorig - avg, barSize, yorig-avg);
g.setStrokeStyle(Graphics.SOLID);
// Restore to left and move down
g.translate(-(w + pad) / 2, pieSize + pad);
// Draw the key and pointer status
g.setColor(128, 128, 128);
int col1 = font.stringWidth("Action:");
g.drawString("Key: ", col1, 0,
Graphics.TOP|Graphics.RIGHT);
g.drawString(keyString(keyCode), col1, 0,
Graphics.TOP|Graphics.LEFT);
g.drawString("Action:", col1, fh,
Graphics.TOP|Graphics.RIGHT);
g.drawString(actionString(keyCode), col1, fh,
Graphics.TOP|Graphics.LEFT);
g.drawString("Event:", col1, fh*2,
Graphics.TOP|Graphics.RIGHT);
g.drawString(event, col1, fh*2,
Graphics.TOP|Graphics.LEFT);
int col2 = 80;
g.drawString("x:", col2, 0,
Graphics.TOP|Graphics.RIGHT);
g.drawString(Integer.toString(x), col2, 0,
Graphics.TOP|Graphics.LEFT);
g.drawString("y:", col2, fh,
Graphics.TOP|Graphics.RIGHT);
g.drawString(Integer.toString(y), col2, fh,
Graphics.TOP|Graphics.LEFT);
// Restore the origin and draw the crosshairs on top
g.translate(-g.getTranslateX(), -g.getTranslateY());
g.setColor(0, 0, 0);
g.drawLine(x, y - 5, x, y + 5);
g.drawLine(x - 5, y, x + 5, y);
}
String keyString(int keyCode) {
if (keyCode == 0) {
return "";
}
return Integer.toString(keyCode);
}
String actionString(int keyCode) {
if (keyCode == 0) {
return "";
}
int action = getGameAction(keyCode);
switch (action) {
case FIRE:
return "Fire";
case LEFT:
return "Left";
case RIGHT:
return "Right";
case DOWN:
return "Down";
case UP:
return "Up";
case GAME_A:
return "Game A";
case GAME_B:
return "Game B";
case GAME_C:
return "Game C";
case GAME_D:
return "Game D";
case 0:
return "";
default:
return Integer.toString(action);
}
}
}
Capture Item Events
/*--------------------------------------------------
* CaptureItemEvents.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CaptureItemEvents extends MIDlet implements ItemStateListener, CommandListener
{
private Display display; // Reference to Display object for this MIDlet
private Form fmMain; // The main Form
private Command cmExit; // A Command to exit the MIDlet
private DateField dfDate; // Display the date
public CaptureItemEvents()
{
display = Display.getDisplay(this);
// Create the date and populate with current date
dfDate = new DateField("Date is:", DateField.DATE);
dfDate.setDate(new java.util.Date());
cmExit = new Command("Exit", Command.EXIT, 1);
// Create the Form, add Command and DateField
// listen for events from Command and DateField
fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.append(dfDate);
fmMain.setCommandListener(this); // Capture Command events (cmExit)
fmMain.setItemStateListener(this); // Capture Item events (dfDate)
}
// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
public void itemStateChanged(Item item)
{
System.out.println("Inside itemStateChanged()");
dfDate.setLabel("New Date: ");
}
}
Commander
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class Commander extends MIDlet {
public void startApp() {
Displayable d = new TextBox("TextBox", "Commander", 20, TextField.ANY);
Command c = new Command("Exit", Command.EXIT, 0);
d.addCommand(c);
d.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
});
Display.getDisplay(this).setCurrent(d);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Commands, Items, and Event Processing
//jad file (please verify the jar size)
/*
MIDlet-Name: ThrowException
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: ThrowException.jar
MIDlet-1: ThrowException, ThrowException.png, ThrowException
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class ThrowException extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("Throw Exception");
private Command exit = new Command("Exit", Command.SCREEN, 1);
private boolean isSafeToQuit = false;
public ThrowException() {
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
if (unconditional == false) {
throw new MIDletStateChangeException();
}
}
public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
try {
if (isSafeToQuit == false) {
StringItem msg = new StringItem("Busy", "Please try again.");
form.append(msg);
destroyApp(false);
} else {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception exception) {
isSafeToQuit = true;
}
}
}
}
Many Commands
/*--------------------------------------------------
* TooManyCommands.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TooManyCommands extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object for this MIDlet
private Form fmMain; // The main Form
private TextBox tbAction; // Textbox to show when user selects upload/download
private Command cmExit; // Exit the MIDlet
private Command cmBack; // Go "back" to the main form
private Command cmUload; // "upload" data - no real action done
private Command cmDload; // "download" data - no real action done
public TooManyCommands()
{
display = Display.getDisplay(this);
cmExit = new Command("Exit", Command.EXIT, 1);
cmBack = new Command("Back", Command.BACK, 1);
cmUload = new Command("Upload", Command.SCREEN, 2);
cmDload = new Command("Download", Command.SCREEN, 3);
// Create the Form, add Commands, listen for events
fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmUload);
fmMain.addCommand(cmDload);
fmMain.setCommandListener(this);
// Create a Textbox, add Command, listen for events
tbAction = new TextBox("Process Data", "Upload/download data ", 25, 0);
tbAction.addCommand(cmBack);
tbAction.setCommandListener(this);
}
// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}
// A required method
public void pauseApp()
{ }
// A required method
public void destroyApp(boolean unconditional)
{ }
// Process events
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
else if (c == cmUload || c == cmDload)
display.setCurrent(tbAction);
else if (c == cmBack)
display.setCurrent(fmMain);
}
}
Mapping Commands
/*--------------------------------------------------
* MappingCommands.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MappingCommands extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object for this MIDlet
private Form fmMain; // Main Form
private TextBox tbHelp; // Textbox to display help message
private Command cmExit; // Exit the MIDlet
private Command cmHelp; // Ask for Help
private Command cmBack; // Go "back" to the main form
public MappingCommands()
{
display = Display.getDisplay(this);
cmHelp = new Command("Help", Command.HELP, 1);
cmBack = new Command("Back", Command.BACK, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
// Create the Form, add Commands, listen for events
fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmHelp);
fmMain.setCommandListener(this);
// Create the help Textbox with a maximum of 25 characters
tbHelp = new TextBox("Help", "Help text here...", 25, 0);
tbHelp.addCommand(cmBack);
tbHelp.setCommandListener(this);
}
// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}
// A required method
public void pauseApp()
{ }
// A required method
public void destroyApp(boolean unconditional)
{ }
// Process events
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
else if (c == cmHelp)
display.setCurrent(tbHelp);
else if (c == cmBack)
display.setCurrent(fmMain);
}
}
Online Help
// jad file
/*
MIDlet-Name: OnlineHelp
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: OnlineHelp.jar
MIDlet-1: OnlineHelp, , OnlineHelp
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
public class OnlineHelp extends MIDlet implements CommandListener {
private Display display;
private Command back = new Command("Back", Command.BACK, 2);
private Command exit = new Command("Exit", Command.EXIT, 1);
private Command help = new Command("Help", Command.HELP, 3);
private Form form = new Form("Online Help Example");
private TextBox helpMesg = new TextBox("Online Help", "Message.", 81, 0);
public OnlineHelp() {
display = Display.getDisplay(this);
helpMesg.addCommand(back);
form.addCommand(exit);
form.addCommand(help);
form.setCommandListener(this);
helpMesg.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == back) {
display.setCurrent(form);
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
} else if (command == help) {
display.setCurrent(helpMesg);
}
}
}
Simple Command Demo
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMIDlet extends MIDlet
implements CommandListener {
// The exit command
private Command exitCommand;
// The display for this MIDlet
private Display display;
// create a ticker
private Ticker hi = new Ticker("J2ME is cool");
public HelloMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.SCREEN, 2);
}
public void startApp() {
TextBox t = new TextBox("Hello MIDlet",
"Wireless Internet", 256, 0);
t.addCommand(exitCommand);
t.setCommandListener(this);
t.setTicker(hi); // set the ticker
display.setCurrent(t);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
Various Event
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class VariousEvent extends MIDlet implements CommandListener {
// display manager
Display display = null;
// a menu with items
List menu = null; // main menu
// list of choices
List choose = null;
// textbox
TextBox input = null;
// ticker
Ticker ticker = new Ticker("Test GUI Components");
// alerts
final Alert soundAlert = new Alert("sound Alert");
// date
DateField date = new DateField("Today"s date: ", DateField.DATE);
// form
Form form = new Form("Form for Stuff");
// gauge
Gauge gauge = new Gauge("Gauge Label", true, 10, 0);
// text field
TextField textfield = new TextField("TextField Label", "abc", 50, 0);
// command
static final Command backCommand = new Command("Back", Command.BACK, 0);
static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
static final Command exitCommand = new Command("Exit", Command.STOP, 2);
String currentMenu = null;
// constructor.
public VariousEvent() {
}
/**
* Start the MIDlet by creating a list of items and associating the
* exit command with it.
*/
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
// open a db stock file
menu = new List("Test Components", Choice.IMPLICIT);
menu.append("Test TextBox", null);
menu.append("Test List", null);
menu.append("Test Alert", null);
menu.append("Test Date", null);
menu.append("Test Form", null);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
menu.setTicker(ticker);
mainMenu();
}
public void pauseApp() {
display = null;
choose = null;
menu = null;
ticker = null;
form = null;
input = null;
gauge = null;
textfield = null;
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
// main menu
void mainMenu() {
display.setCurrent(menu);
currentMenu = "Main";
}
/**
* Test the TextBox component.
*/
public void testTextBox() {
input = new TextBox("Enter Some Text:", "", 5, TextField.ANY);
input.setTicker(new Ticker("testTextBox"));
input.addCommand(backCommand);
input.setCommandListener(this);
input.setString("");
display.setCurrent(input);
currentMenu = "input";
}
/**
* Test the List component.
*/
public void testList() {
choose = new List("Choose Items", Choice.MULTIPLE);
choose.setTicker(new Ticker("listTest"));
choose.addCommand(backCommand);
choose.setCommandListener(this);
choose.append("Item 1", null);
choose.append("Item 2", null);
choose.append("Item 3", null);
display.setCurrent(choose);
currentMenu = "list";
}
/**
* Test the Alert component.
*/
public void testAlert() {
soundAlert.setType(AlertType.ERROR);
soundAlert.setString("** ERROR **");
display.setCurrent(soundAlert);
}
/**
* Test the DateField component.
*/
public void testDate() {
java.util.Date now = new java.util.Date();
date.setDate(now);
Form f = new Form("Today"s date");
f.append(date);
f.addCommand(backCommand);
f.setCommandListener(this);
display.setCurrent(f);
currentMenu = "date";
}
/**
* Test the Form component.
*/
public void testForm() {
form.append(gauge);
form.append(textfield);
form.addCommand(backCommand);
form.setCommandListener(this);
display.setCurrent(form);
currentMenu = "form";
}
/**
* Handle events.
*/
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if (label.equals("Exit")) {
destroyApp(true);
} else if (label.equals("Back")) {
if(currentMenu.equals("list") || currentMenu.equals("input") ||
currentMenu.equals("date") || currentMenu.equals("form")) {
// go back to menu
mainMenu();
}
} else {
List down = (List)display.getCurrent();
switch(down.getSelectedIndex()) {
case 0: testTextBox();break;
case 1: testList();break;
case 2: testAlert();break;
case 3: testDate();break;
case 4: testForm();break;
}
}
}
}