Java/J2ME/List
Содержание
Implicit List
/*--------------------------------------------------
* ImplicitList.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 ImplicitList extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private List lsDocument; // Main list
private Command cmExit; // Command to exit
private Command cmAdd; // Command to add an element
public ImplicitList()
{
display = Display.getDisplay(this);
// Create the Commands
cmExit = new Command("Exit", Command.EXIT, 1);
cmAdd = new Command("Add", Command.SCREEN, 1);
try
{
// Create array of image objects
Image images[] = {Image.createImage("/ff.png"),
Image.createImage("/rr.png"),
Image.createImage("/new.png")};
// Create array of corresponding string objects
String options[] = {" Next", " Previous", " New"};
// Create list using arrays, add commands, listen for events
lsDocument = new List("Document Option:",
List.IMPLICIT, options, images);
lsDocument.addCommand(cmExit);
lsDocument.addCommand(cmAdd);
lsDocument.setCommandListener(this);
}
catch (java.io.IOException e)
{
System.err.println("Unable to locate or read .png file");
}
}
public void startApp()
{
display.setCurrent(lsDocument);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command c, Displayable s)
{
// If an implicit list generated the event
if (c == List.SELECT_COMMAND)
{
switch (lsDocument.getSelectedIndex())
{
case 0:
System.out.println("Next");
break;
case 1:
System.out.println("Previous");
break;
case 2:
System.out.println("New");
break;
default:
System.out.println("New Element");
}
}
else if (c == cmAdd)
{
try
{
System.out.println("lsDocument.size():" + lsDocument.size());
// Add a new element. Using size() as the insertion point,
// the element will appended to the list.
lsDocument.insert(lsDocument.size(), " Delete ",
Image.createImage("/delete.png"));
}
catch (java.io.IOException e)
{
System.err.println("Unable to locate or read .png file");
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}
List CheckBox
//jad file (please verify the jar size)
/*
MIDlet-Name: ListCheckBox
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: ListCheckBox.jar
MIDlet-1: ListCheckBox, , ListCheckBox
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
public class ListCheckBox extends MIDlet implements CommandListener {
private Display display;
private Command exit = new Command("Exit", Command.EXIT, 1);
private Command submit = new Command("Submit", Command.SCREEN, 2);
private List list = new List("Select Media", List.MULTIPLE);
public ListCheckBox() {
display = Display.getDisplay(this);
list.append("Books", null);
list.append("Movies", null);
list.append("Television", null);
list.append("Radio", null);
list.addCommand(exit);
list.addCommand(submit);
list.setCommandListener(this);
}
public void startApp() {
display.setCurrent(list);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable Displayable) {
if (command == submit) {
boolean choice[] = new boolean[list.size()];
StringBuffer message = new StringBuffer();
list.getSelectedFlags(choice);
for (int i = 0; i < choice.length; i++) {
if (choice[i]) {
message.append(list.getString(i));
message.append(" ");
}
}
Alert alert = new Alert("Choice", message.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.INFO);
display.setCurrent(alert);
list.removeCommand(submit);
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
List 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.lcdui.*;
import javax.microedition.midlet.*;
public class ListDemoMIDlet extends MIDlet {
private Display display;
private int mode = List.IMPLICIT;
private Command exitCommand = new Command( "Exit",
Command.SCREEN, 2 );
private Command selectCommand = new Command( "Select",
Command.OK, 1 );
private Command nextCommand = new Command( "Next",
Command.SCREEN, 2 );
public ListDemoMIDlet(){
}
protected void destroyApp( boolean unconditional )
throws MIDletStateChangeException {
exitMIDlet();
}
protected void pauseApp(){
}
protected void startApp() throws
MIDletStateChangeException {
if( display == null ){ // first time called...
initMIDlet();
}
}
private void initMIDlet(){
display = Display.getDisplay( this );
display.setCurrent( new SampleList( mode ) );
}
public void exitMIDlet(){
notifyDestroyed();
}
public static final String[] items = {
"First", "Second", "Third", "Fourth"
};
class SampleList extends List implements
CommandListener {
private int mode;
SampleList( int mode ){
super( "", mode, items, null );
addCommand( exitCommand );
addCommand( selectCommand );
addCommand( nextCommand );
setCommandListener( this );
switch( mode ){
case IMPLICIT:
setTitle( "Implicit" );
break;
case EXCLUSIVE:
setTitle( "Exclusive" );
break;
case MULTIPLE:
setTitle( "Multiple" );
break;
}
this.mode = mode;
}
public void commandAction( Command c,
Displayable d ){
if( c == exitCommand ){
exitMIDlet();
} else if( c == selectCommand ){
showSelection( false );
} else if( c == SELECT_COMMAND ){
showSelection( true );
} else if( c == nextCommand ){
if( mode == List.IMPLICIT ){
mode = List.EXCLUSIVE;
} else if( mode == List.EXCLUSIVE ){
mode = List.MULTIPLE;
} else {
mode = List.IMPLICIT;
}
display.setCurrent( new SampleList(
mode ) );
}
}
private void showSelection( boolean implicit ){
Alert alert = new Alert(
implicit ? "Implicit Selection"
: "Explicit Selection" );
StringBuffer buf = new StringBuffer();
if( mode == MULTIPLE ){
boolean[] selected = new boolean[ size() ];
getSelectedFlags( selected );
for( int i = 0; i < selected.length; ++i ){
if( selected[i] ){
if( buf.length() == 0 ){
buf.append(
"You selected: " );
} else {
buf.append( ", " );
}
buf.append( getString( i ) );
}
}
if( buf.length() == 0 ){
buf.append( "No items are selected." );
}
} else {
buf.append( "You selected " );
buf.append( getString(
getSelectedIndex() ) );
}
alert.setString( buf.toString() );
alert.setTimeout( Alert.FOREVER );
display.setCurrent( alert,display.getCurrent() );
}
}
}
List Implicit
//jad file (please verify the jar size)
/*
MIDlet-Name: ListImplicit
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: ListImplicit.jar
MIDlet-1: ListImplicit, , ListImplicit
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
public class ListImplicit extends MIDlet implements CommandListener {
private Display display;
private List list = new List("Menu:", List.IMPLICIT);
private Command exit = new Command("Exit", Command.EXIT, 1);
Alert alert;
public ListImplicit() {
display = Display.getDisplay(this);
list.append("New", null);
list.append("Open", null);
list.addCommand(exit);
list.setCommandListener(this);
}
public void startApp() {
display.setCurrent(list);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == List.SELECT_COMMAND) {
String selection = list.getString(list.getSelectedIndex());
alert = new Alert("Option Selected", selection, null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.INFO);
display.setCurrent(alert);
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
List Item MIDlet
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Screen;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class ItemMIDlet extends MIDlet
implements CommandListener, ItemStateListener {
// The MIDlet"s Display object
private Display display;
// Flag indicating first call of startApp
protected boolean started;
// Exit command
private Command exitCommand;
// Back to examples list command
private Command backCommand;
// The example selection list
private List examplesList;
// The Screens used to demonstrate different Items
private Screen[] screens;
// The example names. Used to populate the list.
private String[] examples = {
"StringItem", "TextField", "DateField",
"ImageItem", "Gauge", "ChoiceGroup",
"List", "Alert", "Sounds"
};
// List of alert types
private AlertType[] alertTypes = new AlertType[] {
AlertType.ALARM, AlertType.CONFIRMATION, AlertType.ERROR,
AlertType.INFO, AlertType.WARNING, null
};
private String[] alertTypeNames = new String[] {
"ALARM", "CONFIRMATION", "ERROR", "INFO", "WARNING", "None"
};
protected void startApp() {
if (!started) {
started = true;
display = Display.getDisplay(this);
// Create the common commands
createCommands();
// Create the screens
createScreens();
// Create the list of examples
createList();
// Start with the List
display.setCurrent(examplesList);
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (d == examplesList) {
// New example selected
int index = examplesList.getSelectedIndex();
display.setCurrent(screens[index]);
} else if (c == exitCommand) {
// Exit. No need to call destroyApp
// because it is empty.
notifyDestroyed();
} else if (c == backCommand) {
// Go back to main selection list
display.setCurrent(examplesList);
} else if (c == List.SELECT_COMMAND) {
// Selection made in the IMPLICIT LIST
handleChoiceSelection((Choice)d);
}
}
public void itemStateChanged(Item item) {
if (item instanceof TextField) {
System.out.println("Text field content: <" +
((TextField)item).getString() + ">");
} else if (item instanceof DateField) {
DateField df = (DateField)item;
Date date = df.getDate();
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("Date field content set to " + date);
} else {
System.out.println("Date field content set to null");
}
} else if (item instanceof Gauge) {
int value = ((Gauge)item).getValue();
System.out.println("Gauge value set to " + value);
} else if (item instanceof ChoiceGroup) {
handleChoiceSelection((Choice)item);
} else {
System.out.println("Item state changed in " + item);
}
}
private void createCommands() {
exitCommand = new Command("Exit", Command.EXIT, 0);
backCommand = new Command("Back", Command.BACK, 1);
}
private void createList() {
examplesList = new List("Select Example", List.IMPLICIT);
for (int i = 0; i < examples.length; i++) {
examplesList.append(examples[i], null);
}
examplesList.setCommandListener(this);
}
private void createScreens() {
screens = new Screen[examples.length];
screens[0] = createStringsForm();
screens[1] = createTextFieldForm();
screens[2] = createDateFieldForm();
screens[3] = createImageItemForm();
screens[4] = createGaugeForm();
screens[5] = createChoiceGroupForm();
screens[6] = createListExample();
screens[7] = createAlertForm();
screens[8] = createSoundsForm();
}
private void addCommands(Displayable d) {
d.addCommand(exitCommand);
d.addCommand(backCommand);
d.setCommandListener(this);
if (d instanceof Form) {
((Form)d).setItemStateListener(this);
}
}
// Example for StringItem
private Form createStringsForm() {
Form form = new Form("StringItem");
form.append(new StringItem("State ", "OK"));
form.append(new StringItem(null, "No label\n"));
form.append(new StringItem(null, "Line\nbreak"));
form.append(new StringItem("Label", "Text."));
form.append(new StringItem("Label2 ", "Text2."));
addCommands(form);
return form;
}
// Example for TextField
private Form createTextFieldForm() {
Form form = new Form("TextField");
form.append(new TextField("Any", null, 8, TextField.ANY));
form.append(new TextField("Phone", "1234567890", 10, TextField.PHONENUMBER));
form.append(new TextField("Number", "12345", 8, TextField.NUMERIC));
form.append(new TextField("Password", null, 8, TextField.PASSWORD | TextField.NUMERIC));
addCommands(form);
return form;
}
// Example for DateField
private Form createDateFieldForm() {
Form form = new Form("DateField");
// Get Calendar for the epoch date and time
Calendar baseCal = Calendar.getInstance();
Date baseDate = new Date(0);
baseCal.setTime(baseDate);
// Get Calendar for now and use the epoch
// values to reset the date to the epoch.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
cal.set(Calendar.YEAR, baseCal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, baseCal.get(Calendar.MONTH));
cal.set(Calendar.DATE, baseCal.get(Calendar.DATE));
DateField timeOnly = new DateField("Time", DateField.TIME);
DateField dateOnly = new DateField("Date", DateField.DATE);
DateField both = new DateField("Both", DateField.DATE_TIME);
timeOnly.setDate(cal.getTime());
dateOnly.setDate(now);
both.setDate(now);
form.append(timeOnly);
form.append(dateOnly);
form.append(both);
addCommands(form);
return form;
}
// Example for ImageItem
private Form createImageItemForm() {
Form form = new Form("ImageItem");
try {
Image red = Image.createImage("/ora/ch4/resources/red.png");
Image blue = Image.createImage("/ora/ch4/resources/blue.png");
// ImageItems with labels
// (1)
form.append(new ImageItem("Center", red, ImageItem.LAYOUT_CENTER, null));
// (2)
form.append(new ImageItem("Left", red, ImageItem.LAYOUT_LEFT, null));
// (3)
form.append(new ImageItem("Right", red, ImageItem.LAYOUT_RIGHT, null));
// (4)
form.append(new ImageItem("Default", red, ImageItem.LAYOUT_DEFAULT, null));
// ImageItems with no labels
// (5)
form.append(new ImageItem(null, blue,
ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_CENTER |
ImageItem.LAYOUT_NEWLINE_AFTER, null));
// (6)
form.append(new ImageItem(null, blue,
ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_DEFAULT |
ImageItem.LAYOUT_NEWLINE_AFTER, null));
// (7)
form.append(new ImageItem(null, blue,
ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_RIGHT |
ImageItem.LAYOUT_NEWLINE_AFTER, null));
// (8)
form.append(new ImageItem(null, blue, ImageItem.LAYOUT_DEFAULT, null));
form.append(new ImageItem(null, blue, ImageItem.LAYOUT_DEFAULT, null));
} catch (IOException ex) {
form.append("Failed to load images");
}
addCommands(form);
return form;
}
// Example for Gauge
private Form createGaugeForm() {
Form form = new Form("Gauge");
form.append(new Gauge(null, true, 100, 50));
form.append(new Gauge(null, true, 100, 25));
form.append(new Gauge(null, false, 100, 50));
addCommands(form);
return form;
}
// Example for ChoiceGroup
private Form createChoiceGroupForm() {
Form form = new Form("ChoiceGroup");
try {
Image red = Image.createImage("/ora/ch4/resources/red.png");
Image green = Image.createImage("/ora/ch4/resources/green.png");
Image blue = Image.createImage("/ora/ch4/resources/blue.png");
// Exclusive choice group
String[] strings = new String[] { "Red", "Green", "Blue" };
Image[] images = new Image[] { red, green, blue };
ChoiceGroup exGroup = new ChoiceGroup("Choose one", ChoiceGroup.EXCLUSIVE,
strings, images);
form.append(exGroup);
// Multiple choice group
ChoiceGroup multiGroup = new ChoiceGroup("Choose any", ChoiceGroup.MULTIPLE);
form.append(multiGroup);
multiGroup.append("Use SSL", null);
multiGroup.append("Reconnect on failure", null);
multiGroup.append("Enable tracing", null);
} catch (IOException ex) {
form.append("Failed to load images");
}
addCommands(form);
return form;
}
// Example for List
private Screen createListExample() {
List list = new List("List", List.IMPLICIT);
try {
Image red = Image.createImage("/ora/ch4/resources/red.png");
Image green = Image.createImage("/ora/ch4/resources/green.png");
Image blue = Image.createImage("/ora/ch4/resources/blue.png");
list.append("Red", red);
list.append("Green", green);
list.append("Blue", blue);
} catch (IOException ex) {
Form form = new Form("Error");
form.append("Failed to load images");
return form;
}
addCommands(list);
return list;
}
// Example for Alert
private Screen createAlertForm() {
final Form form = new Form("Alert");
// A ChoiceGroup that allows the user to choose between
// a modal Alert or an Alert with a finite timeout.
final ChoiceGroup limitGroup = new ChoiceGroup("Timeout", Choice.EXCLUSIVE);
limitGroup.append("Forever", null);
limitGroup.append("Bounded 5s", null);
form.append(limitGroup);
// A Gauge that allows the user to choose the
// timeout for the Alert. This appears only if
// the "Bounded" option is selected.
final Gauge gauge = new Gauge(null, true, 30, 5);
// A ChoiceGroup that lets the user pick the
// type of Alert
final ChoiceGroup group = createAlertChoiceGroup(true);
form.append(group);
// A Command that is used to display the Alert
final Command okCommand = new Command("OK", Command.OK, 0);
// Add CommandListener for back/exit commands
// and the OK command, which is specific to this Form
form.addCommand(okCommand);
form.addCommand(exitCommand);
form.addCommand(backCommand);
form.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == okCommand) {
// Create and display the Alert
// Get the alert type from the
// second ChoiceGroup
int selectedType = group.getSelectedIndex();
AlertType alertType = alertTypes[selectedType];
String name = alertTypeNames[selectedType];
// Get the timeout. This is FOREVER if the
// first item in the first ChoiceGroup is
// selected. Otherwise it is the value in
// the Gauge
int timeout = Alert.FOREVER;
String timeoutString = "none";
if (limitGroup.isSelected(1)) {
// "Bounded" selected - get the timeout.
timeout = gauge.getValue() * 1000;
timeoutString = gauge.getValue() + "s";
}
// Create the Alert and set the timeout
Alert alert = new Alert("Alert!",
"Alert type: " + name + "\nTimeout = " + timeoutString,
null, alertType);
alert.setTimeout(timeout);
// Display the Alert.
display.setCurrent(alert);
} else {
// Delegate others to the usual commandAction
ItemMIDlet.this.rumandAction(c, d);
}
}
});
// Set our own ItemStateListener
form.setItemStateListener(new ItemStateListener() {
public void itemStateChanged(Item item) {
if (item == limitGroup) {
if (limitGroup.getSelectedIndex() == 0) {
// Get rid of the Gauge
form.delete(1);
} else {
// Add the Gauge
form.insert(1, gauge);
}
} else if (item == gauge) {
int value = gauge.getValue();
limitGroup.set(1, "Bounded " + value + "s", null);
}
}
});
return form;
}
// Example for Sounds
private Screen createSoundsForm() {
final Form form = new Form("Sounds");
// A ChoiceGroup that lets the user pick the
// type of sound
final ChoiceGroup group = createAlertChoiceGroup(false);
form.append(group);
addCommands(form);
// Set our own ItemStateListener
form.setItemStateListener(new ItemStateListener() {
public void itemStateChanged(Item item) {
// Get the alert type from the ChoiceGroup
int selectedType = group.getSelectedIndex();
AlertType alertType = alertTypes[selectedType];
boolean result = alertType.playSound(display);
System.out.println("A sound was " + (result ? "" : "not ")
+ "played.");
}
});
return form;
}
// Handles the selection for a Choice
private void handleChoiceSelection(Choice choice) {
int count = choice.size();
boolean[] states = new boolean[count];
int selCount = choice.getSelectedFlags(states);
if (selCount > 0) {
System.out.println("Selected items:");
for (int i = 0; i < count; i++) {
if (states[i]) {
System.out.println("\t" + choice.getString(i));
}
}
} else {
System.out.println("No selected items.");
}
int selectedIndex = choice.getSelectedIndex();
System.out.println("Selected index is " + selectedIndex);
}
// Creates a ChoiceGroup containing a set of Alert types
private ChoiceGroup createAlertChoiceGroup(boolean includeNone) {
ChoiceGroup group = new ChoiceGroup("Alert Type", Choice.EXCLUSIVE);
int count = includeNone ? alertTypeNames.length : alertTypeNames.length - 1;
for (int i = 0; i < count; i++) {
group.append(alertTypeNames[i], null);
}
return group;
}
}
multiple Choice List
/*--------------------------------------------------
* MultipleChoiceList.java
*
* Create multiple choice list and save selection
* status of each element in an array.
*
* 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 MultipleChoiceList extends MIDlet implements CommandListener
{
private Display display; // Reference to display object
private Command cmExit; // A Command to exit the MIDlet
private Command cmView; // View the choice selected
private List lsPrefs; // Choice Group of preferences
public MultipleChoiceList()
{
display = Display.getDisplay(this);
// Create a multiple choice list
lsPrefs = new List("Preferences", List.MULTIPLE);
// Append options, with no associated images
lsPrefs.append("Auto Indent", null);
lsPrefs.append("Replace Tabs", null);
lsPrefs.append("Wrap Text", null);
cmExit = new Command("Exit", Command.EXIT, 1);
cmView = new Command("View", Command.SCREEN,2);
// Add commands, listen for events
lsPrefs.addCommand(cmExit);
lsPrefs.addCommand(cmView);
lsPrefs.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(lsPrefs);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmView)
{
boolean selected[] = new boolean[lsPrefs.size()];
// Fill array indicating whether each element is checked
lsPrefs.getSelectedFlags(selected);
for (int i = 0; i < lsPrefs.size(); i++)
System.out.println(lsPrefs.getString(i) + (selected[i] ? ": selected" : ": not selected"));
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}
Payment MIDlet
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class PaymentMIDlet extends MIDlet {
private Display display;
List options = null;
public PaymentMIDlet() {
options = new List("Method of Payment", Choice.EXCLUSIVE);
}
public void startApp() {
display = Display.getDisplay(this);
options.append("Visa", null);
options.append("MasterCard", null);
options.append("Amex", null);
display.setCurrent(options);
}
/**
* 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) {
}
}
Travel List
import java.io.IOException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
public class TravelList extends MIDlet implements CommandListener {
private List mList;
private Command mExitCommand, mNextCommand;
public TravelList() {
String[] stringElements = { "A", "B", "C" };
Image[] imageElements = { loadImage("/airplane.png"), loadImage("/car.png"),
loadImage("/hotel.png") };
mList = new List("Reservation type", List.IMPLICIT, stringElements, imageElements);
mNextCommand = new Command("Next", Command.SCREEN, 0);
mExitCommand = new Command("Exit", Command.EXIT, 0);
mList.addCommand(mNextCommand);
mList.addCommand(mExitCommand);
mList.setCommandListener(this);
}
public void startApp() {
Display.getDisplay(this).setCurrent(mList);
}
public void commandAction(Command c, Displayable s) {
if (c == mNextCommand || c == List.SELECT_COMMAND) {
int index = mList.getSelectedIndex();
Alert alert = new Alert("Your selection", "You chose " + mList.getString(index) + ".", null,
AlertType.INFO);
Display.getDisplay(this).setCurrent(alert, mList);
} else if (c == mExitCommand)
notifyDestroyed();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private Image loadImage(String name) {
Image image = null;
try {
image = Image.createImage(name);
} catch (IOException ioe) {
System.out.println(ioe);
}
return image;
}
}