Java Programming Notes # 2582
- Preface
- General background information
- Discussion and sample code
- Run the program
- Summary
- What’s next?
- Resources
- Complete program listing
- Copyright
- About the author
Preface
This is one in a series of tutorial lessons designed to teach you how to write programs using the Sun Java Wireless Toolkit for CLDC. The first lesson was titled Getting Started with MIDlets and the Sun Java Wireless Toolkit for CLDC. The previous lesson was titled Using Alerts, Images, Timers, and Gauges in MIDlets (see Resources).
What you will learn
In this lesson, you will learn about the Choice interface and the List class, which implements the Choice interface. You will learn about the composition of a Choice object. You will learn about implicit, exclusive, and multiple Choice types. You will learn about the selected state of a Choice element of each of the different types. You will learn how to create a List, how to display it in the Sun cell phone emulator, and how to determine which elements in the List are selected.
A MIDlet development framework
For this lesson, you will need the updated version of the MIDlet development framework named WTKFramework03, which was provided in the earlier lesson titled Using Alerts, Images, Timers, and Gauges in MIDlets (see Resources).
Viewing tip
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
Figures
- Figure 1. Partial class hierarchy for MIDP 2.0.
- Figure 2. Methods of the Choice interface as declared in MIDP 2.0.
- Figure 3. An implicit List object in the cell phone emulator.
- Figure 4. Partial standard output for List01 and an implicit List object.
- Figure 5. An exclusive List object in the cell phone emulator.
- Figure 6. Partial standard output for List01 and an exclusive List object.
- Figure 7. A multiple choice List object in the cell phone emulator.
- Figure 8. Partial standard output for List01 and a multiple choice List object.
- Figure 9. Additional methods of the List class.
Listings
- Listing 1. Beginning of the class for the MIDlet named List01.
- Listing 2. The constructor for the MIDlet named List01.
- Listing 3. The startApp method for the MIDlet named List01.
- Listing 4. The destroyApp method for the MIDlet named List01.
- Listing 5. The complete MIDlet program named List01.
Supplementary material
I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find a consolidated index at www.DickBaldwin.com.
General background information
A partial class hierarchy for MIDP 2.0 is shown in Figure 1.
Figure 1. Partial class hierarchy for MIDP 2.0.
|
I have discussed and illustrated the classes shown in boldface Italics in earlier lessons. I will discuss and illustrate the List class and the Choice interface in this lesson. I will discuss and illustrate the Form, Item, ChoiceGroup, Canvas and GameCanvas classes in future lessons.
The Choice interface
The List class implements the Choice interface. To understand a class, you must understand the interfaces that it implements.
According to Sun,
“Choice defines an API for a user interface components implementing selection from predefined number of choices. Such UI components are List and ChoiceGroup. The contents of the Choice are represented with strings and images.”
An indexed object
Elements within a Choice object are referred to by their indices. The indices are consecutive integers in the range from zero to one less than the value returned by the size method. An index of zero refers to the first element.
The parts of a Choice element
Each element of a Choice is composed of the following parts:
- A text string part
- An Image part
- A font attribute
Getter and setter methods are provided for all three parts. As you might expect, the font attribute applies to the text string part.
Elements may be inserted, appended, and deleted after a Choice object has been created.
The Image
If there is an image, the cell phone displays the image at the beginning of the text string as shown by the red, green, and blue ball images in Figure 3.
Some Choice components use selection indicators such as a radio button or a checkbox as shown in Figure 5 and Figure 7. When a selection indicator is present, the image is placed between the selection indicator and the beginning of the text string.
Types of Choice objects
The boldface text in Figure 4 shows the result of querying the system to determine and display the string part of the selected elements in the List shown in Figure 3. The output shown in Figure 4 is the value of the string part of the selected element in Figure 3.
An exclusive List object
Figure 5 shows an exclusive List object. Note that the List element with a string part of “One” is both highlighted and selected.
Figure 5. An exclusive List object in the cell phone emulator.
Selecting an element
The Sun cell phone emulator uses radio buttons to indicate which element is selected. To select an element, navigate to that element using the up and down arrow keys on the cell phone emulator keypad and then click the large square button that is surrounded by arrows. This causes the radio button associated with the highlighted element to indicate that the element is selected.
The corresponding standard output
Figure 6 shows a partial listing of the standard output for the exclusive List object shown in Figure 5. The boldface text in Figure 6 matches the selected element in Figure 5.
Figure 6. Partial standard output for List01 and an exclusive List object.
OUT: Construct MIDlet OUT: Construct Image objects OUT: Create List OUT: Populate list OUT: Display list OUT: Identify selected elements OUT: Selected: One OUT: Destroy MIDlet |
A multiple choice List object
Figure 7 shows a multiple choice List object. Note that two of the elements have check marks in the squares to the left of the string.
Figure 7. A multiple choice List object in the cell phone emulator.
Selecting elements
This type of List object allows the user to select none, one, or more elements in any combination. To select an element, navigate to the element using the up and down arrow keys and then click the large square button. This will place a check mark in the square on the cell phone display indicating that the element is selected. To de-select an element that was previously selected, navigate to the selected element and click the large square button. That will cause the check mark to disappear.
The corresponding standard output
Figure 8 shows a partial listing of the standard output for the multiple choice List shown in Figure 7. Note that the two elements identified as being selected in Figure 8 match the checked elements in Figure 7.
Figure 8. Partial standard output for List01 and a multiple choice List object.
OUT: Construct MIDlet OUT: Construct Image objects OUT: Create List OUT: Populate list OUT: Display list OUT: Identify selected elements OUT: Selected: Zero OUT: Selected: Two OUT: Destroy MIDlet |
What is a List?
According to Sun, a List is
“A Screen containing list of choices. … When a List is present on the display, the user can interact with it by selecting elements and possibly by traversing and scrolling among them.”
Types of Lists
The List class implements the Choice interface. List objects may be created with Choice types of
- Choice.EXCLUSIVE
- Choice.MULTIPLE
- Choice.IMPLICIT
You learned about these different types in the earlier discussion of the Choice interface. (Note that the Choice.POPUP type is valid only for ChoiceGroup, will be discussed in a future lesson.)
Selection
The mechanics of selecting List elements may vary from one cell phone to the next. For the Sun cell phone emulator, a List element is selected by first highlighting the element using the up and down arrow keys and then clicking the large square button shown in Figure 3.
In an EXCLUSIVE List, the select operation selects the highlighted element and deselects the previously selected element. In a MULTIPLE List, the select operation toggles the selected state of the target element, leaving the selected state of other elements unchanged. In an IMPLICIT List, no explicit select operation is required. The highlighted element is implicitly selected.
Constructors for the List class
There are two overloaded constructors for the List class. One of the constructors requires the following four parameters:
- String title
- int listType (Choice.EXCLUSIVE, Choice.MULTIPLE, or Choice.IMPLICIT)
- String[] stringElements
- Image[] imageElements
The other constructor requires only the first two parameters shown above.
The first two parameters in the above list of constructor parameters are self-explanatory.
The last two parameters allow the programmer to pass references to two array objects that contain references to the String parts and the Image parts for all of the elements that will initially appear in the List. Regardless of which constructor is used to construct the List, elements can later be added to or deleted from the List using the first eight methods shown in Figure 2.
Methods of the List class
The List class defines all of the Choice interface methods shown in Figure 2 plus the four methods shown in Figure 9.
Figure 9. Additional methods of the List class.
|
I will have more to say about commands and interactive MIDlets in a future lesson. I will discuss methods similar to the first two methods in Figure 9 at that time.
You learned about the use of a Ticker object in the earlier lesson titled Introduction to the MIDlet User Interface, Part 1 (see Resources). Therefore, the method named setTicker shouldn’t require further explanation. The method named setTitle is self-explanatory.
Discussion and sample code
|
The MIDlet named List01
The purpose of this MIDlet is to illustrate the creation and processing of a List user interface object. The processing of the List consists simply of determining and displaying which elements of the List are selected.
Three types are illustrated
You can add and remove comment indicators in the MIDlet code to activate any one of three statements to create a List object having one of the following Choice types:
- IMPLICIT
- EXCLUSIVE
- MULTIPLE
Operation
The MIDlet displays the List using the Sun cell phone emulator (see Figures 3, 5, and 7) and allows the user twenty seconds to select one or more list elements. Then the MIDlet identifies and displays the selected elements on the standard output device immediately before entering the destroyed state.
Selecting elements
Using the Sun cell phone emulator, you can highlight a List element using the up and down arrow keys on the emulator keypad (also see the sidebar).
For the IMPLICIT type of List, the highlighted element is also the selected element. For the EXCLUSIVE and MULTIPLE types of List, you must make the selection by first highlighting the element and then clicking the large button on the cell phone emulator keypad that is surrounded by arrow keys (see Figure 3).
Will discuss in fragments
As is my custom, I will present and explain the code in this MIDlet in fragments. A complete listing of the MIDlet is presented in Listing 5 near the end of the lesson.
Beginning of the class
Listing 1 shows the beginning of the class for the MIDlet named List01.
Listing 1. Beginning of the class for the MIDlet named List01.
public class List01 extends MIDlet{ Image redBallImage; Image greenBallImage; Image blueBallImage; List list; |
Instance variables
|
The class begins by declaring several instance variables, including three variables of type Image that will be used to represent the red, green, and blue ball images shown in Figure 3. To run this MIDlet, you will need to put three small image files in the same directory as the source code. You can either give the files the following names, or you can modify the code in Listing 2 to match the names of your image files:
- blueball.PNG
- greenball.PNG
- redball.PNG
The constructor
Listing 2 shows the constructor in its entirety.
Listing 2. The constructor for the MIDlet named List01.
public List01(){//constructor System.out.println("Construct MIDlet"); try{ System.out.println("Construct Image objects"); //Make certain that the image files specified // below are in the same directory as the source // file. redBallImage = Image.createImage( "/List01/redball.PNG"); greenBallImage = Image.createImage( "/List01/greenball.PNG"); blueBallImage = Image.createImage( "/List01/blueball.PNG"); }catch(Exception e){ e.printStackTrace(); }//end catch System.out.println("Create List"); //Activate one and only one of the following // statements to create a List with the specified // choice type. //list = new List("List Title",Choice.IMPLICIT); list = new List("List Title",Choice.EXCLUSIVE); //list = new List("List Title",Choice.MULTIPLE); }//end constructor |
You learned about images in the earlier lesson titled Using Alerts, Images, Timers, and Gauges in MIDlets (see Resources). Therefore, the code in Listing 2 involving images should not require further explanation.
Construct a List object
The last statement in Listing 2 constructs a new List object using the version of the constructor that requires only two parameters: the title and the type.
Note that only one of the List constructor statements shown in Listing 2 should be activated by adding and removing comment indicators. By activating each of these three statements one at a time, you should be able to replicate the output shown on the Sun cell phone emulator in Figures 3, 5, and 7 (except that your images will probably be different).
The startApp method
The startApp method is shown in its entirety in Listing 3.
Listing 3. The startApp method for the MIDlet named List01.
public void startApp(){ System.out.println("Populate list"); list.append("Zero",redBallImage); list.append("One",greenBallImage); list.append("Two",blueBallImage); //Make the List be the current display. System.out.println("Display list"); Display.getDisplay(this).setCurrent(list); //Sleep for 20 seconds. try{Thread.currentThread().sleep(20000); } catch(Exception e){} //Enter the destroyed state. this.destroyApp(true); }//end startApp |
You should already know the purpose of the startApp method
I am assuming that by now you will have studied the earlier lessons in this series (see Resources) and it should no longer be necessary for me to describe the purpose of the methods named
- startApp
- pauseApp
- destroyApp
Populate, display, sleep, and destroy the MIDlet
Listing 3 makes three calls to the append method described in Figure 2 to populate the List object with the text strings and images shown in Figure 3.
Then the startApp method in Listing 3 causes the List to become the current Displayable object and goes to sleep for twenty seconds. Upon awakening at the end of twenty seconds, the startApp method calls the destroyApp method to cause the MIDlet to enter the destroyed state.
The pauseApp method
The pauseApp method is empty in this MIDlet. You can view the empty method in Listing 5.
The destroyApp method
The destroyApp method is shown in its entirety in Listing 4. Note that the incoming parameter to the destroyApp method is ignored by the code in Listing 4.
Listing 4. The destroyApp method for the MIDlet named List01.
public void destroyApp(boolean unconditional){ System.out.println("Identify selected elements"); for(int cnt = 0;cnt < list.size();cnt++){ if(list.isSelected(cnt)){ System.out.println( "Selected: " + list.getString(cnt)); }//end if }//end for loop System.out.println("Destroy MIDlet"); notifyDestroyed(); }//end destroyApp }//end class List01 |
Identify and display the selected elements
Listing 4 uses a call to the isSelected method described in Figure 2 inside a for loop to test each element and determine if the element is selected. If so, a message to that effect is displayed on the standard output device as shown in Figure 8. Once an element has been identified as being selected, the getString method is called to get the text string part of the element. The text string is used to construct the message.
Enter the destroyed state
After displaying the selected elements, the destroyApp method calls the notifyDestroyed method to signal the AMS that the MIDlet is entering the destroyed state.
End of the MIDlet
Listing 4 also signals the end of the MIDlet class named List01.
Run the program
I encourage you to copy the MIDlet code from Listing 5. Run the MIDlet in the updated MIDlet development framework named WTKFramework03 that I provided in the lesson titled Using Alerts, Images, Timers, and Gauges in MIDlets (see Resources). Experiment with the MIDlet code, making changes and running your modified MIDlets in conjunction with the framework program. See if you can explain the results produced by your changes.
Don’t forget that you will need to download and install the latest version of the Sun Java Wireless Toolkit for CLDC (see Resources). As of the date this lesson is being written, the latest version of the toolkit is WTK2.5.2. In addition you will need three small image files to replace the red, green, and blue ball images in Figure 3.
Summary
In this lesson, you learned about the Choice interface and the List class, which implements the Choice interface. You learned that a Choice object is composed of a text string, an image, and a font attribute. You learned about implicit, exclusive, and multiple Choice types. You learned about the selected state of a Choice element of each of the different types. You learned how to create a List, how to display it in the Sun cell phone emulator, and how to determine which elements in the List are selected.
What’s next?
In the next lesson, you will learn about the class named Item. Then you will learn how to create a Form and how to populate it with objects of the following classes: String, StringItem, Image, ImageItem, ChoiceGroup, DateField, Gauge (interactive), Gauge (non-interactive), Spacer, and TextField. You will also learn about layout directives and appearance modes.
Resources
- Download Sun Java Wireless Toolkit 2.5 for CLDC Release
- MIDlet: From Wikipedia, the free encyclopedia
- MIDlet: According to SCMAD Certification Center
- J2ME Tutorial, Part 1: Creating MIDlets by Vikram Goyal
- Pre-verifying MIDlet code according to Vikram Goyal
- Deploying a MIDlet according to Vikram Goyal
- The Java ME Device Table
- Retrieving MIDlet Attributes by Richard Marejka
- Learning Path: MIDlet Life Cycle
- When Runtime.exec() won’t By Michael C. Daconta
- Connected Limited Device Configuration (CLDC) from Wikipedia
- Mobile Information Device Profile (MIDP) from Wikipedia
- Online API documentation for CLDC 1.0
- Online API documentation for CLDC 1.1
- Online API documentation for MIDP 1.0
- Online API documentation for MIDP 2.0
- Free Online Image Converter
- 2570 Getting Started with MIDlets and the Sun Java Wireless Toolkit for CLDC
- 2572 Capturing Output Produced by Programs Running in a Child Process
- 2574 Back to Basics with MIDlets and the Sun Java Wireless Toolkit for CLDC
- 2576 Introduction to the MIDlet User Interface, A First Look
- 2578 Handling Life-Cycle Issues with the MIDlet User Interface
- 2580 Using Alerts, Images, Timers, and Gauges in MIDlets
Complete program listing
A complete listing of the MIDlet program discussed in this lesson is shown in Listing 5 below.
Listing 5. The complete MIDlet program named List01.
/*List01.java Copyright 2007, R.G.Baldwin The purpose of this program is to illustrate the creation and simple processing of a List user interface object. Add and remove comment indicators to activate one of three given statements to create a List object having one of the following Choice types: IMPLICIT EXCLUSIVE MULTIPLE The MIDlet displays the list and allows the user twenty seconds to select one or more list elements. Then it identifies and displays the selected elements on the standard output device immediately before entering the destroyed state.. Using the Sun cell phone emulator, you can highlight a List item using the up and down arrow keys. For IMPLICIT, the highlighted item is also the selected item. For EXCLUSIVE and MULTIPLE, make the selection by first highlighting the item and then clicking the large button on the cell phone emulator keypad that is surrounded by arrow keys. Tested using a Java SE 6 compiler, targeted at a V1.4 virtual machine, and WTK 2.5.2 running under Windows XP. *********************************************************/ package List01; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.List; import javax.microedition.lcdui.Choice; import javax.microedition.midlet.MIDlet; import javax.microedition.lcdui.Image; public class List01 extends MIDlet{ Image redBallImage; Image greenBallImage; Image blueBallImage; List list; //----------------------------------------------------// public List01(){//constructor System.out.println("Construct MIDlet"); try{ System.out.println("Construct Image objects"); //Make certain that the image files specified // below are in the same directory as the source // file. redBallImage = Image.createImage( "/List01/redball.PNG"); greenBallImage = Image.createImage( "/List01/greenball.PNG"); blueBallImage = Image.createImage( "/List01/blueball.PNG"); }catch(Exception e){ e.printStackTrace(); }//end catch System.out.println("Create List"); //Activate one and only one of the following // statements to create a List with the specified // choice type. //list = new List("List Title",Choice.IMPLICIT); list = new List("List Title",Choice.EXCLUSIVE); //list = new List("List Title",Choice.MULTIPLE); }//end constructor //----------------------------------------------------// public void startApp(){ System.out.println("Populate list"); list.append("Zero",redBallImage); list.append("One",greenBallImage); list.append("Two",blueBallImage); //Make the List be the current display. System.out.println("Display list"); Display.getDisplay(this).setCurrent(list); //Sleep for 20 seconds. try{Thread.currentThread().sleep(20000); } catch(Exception e){} //Enter the destroyed state. this.destroyApp(true); }//end startApp //----------------------------------------------------// public void pauseApp(){ }//end pauseApp //----------------------------------------------------// public void destroyApp(boolean unconditional){ System.out.println("Identify selected elements"); for(int cnt = 0;cnt < list.size();cnt++){ if(list.isSelected(cnt)){ System.out.println( "Selected: " + list.getString(cnt)); }//end if }//end for loop System.out.println("Destroy MIDlet"); notifyDestroyed(); }//end destroyApp //----------------------------------------------------// }//end class List01 |
Copyright
Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
About the author
Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin’s Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor’s degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.