Published: April 22, 2008
By Richard G. Baldwin
Java Programming Notes # 2582
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).
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.
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.
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 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:
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
There are four types of Choice objects:
The exclusive choice
The exclusive choice (see Figure 5) presents a list of elements and allows the user to select only one. The selected element is shown to be selected using a distinct visual representation (such as a radio button in the Sun cell phone emulator). One element is always selected if the Choice is not empty.
The implicit choice
The implicit choice (see Figure 3) is an exclusive choice where the focused or highlighted element is implicitly the selected element. One element is always selected if the Choice is not empty.
The multiple choice
A multiple choice (see Figure 7) allows the user to select none, one, or more elements in any combination among the elements in the Choice. The appearance of a multiple choice object should have a visual representation (such as the check boxes in the Sun cell phone emulator) that is distinct from the exclusive choice object. The visual indicator shows the selected state of each element and also indicates to the user that multiple elements may be selected. There is no requirement for an element to be selected in the multiple choice type. In other words, it is allowable for none of the elements to be selected even when the Choice is not empty.
The pop-up choice
I will discuss this choice in more detail in a future lesson in conjunction with the Form class.
The selected state of an element
The selected state of an element is a property of the element and is not dependent upon the current index of the element. For example, the selected state stays with that element even if other elements are inserted or deleted.
When a new element is inserted or appended, it is always unselected (except for the special case of adding an element to an empty exclusive, pop-up, or implicit Choice).
Setting and querying the selected state
The selected state of an entire Choice object can be set by the MIDlet code using the setSelectedFlags and setSelectedIndex methods.
The selected state of the entire Choice object can be determined by the MIDlet using the getSelectedFlags and getSelectedIndex methods.
The selected state of any particular element can be determined using the isSelected method.
Methods of the Choice interface in MIDP 2.0
Figure 2 shows a list and a brief description of each of the methods declared in MIDP 2.0. As you should already be aware, all classes that implement the interface must provide concrete definitions for all of the interface methods or the implementing class must be declared abstract. The List class is not abstract so it must provide a concrete definition of all the methods in Figure 2.
Figure 2. Methods of the Choice interface as declared in MIDP 2.0.
|
Methods are separated into groups
I have separated the methods in Figure 2 into three functional groups to make it easier to understand them. The eight methods in the first group are used to populate (or de-populate) the Choice object in a variety of different ways.
The eight methods in the middle group are used to query the Choice object to get the values of a variety of properties.
The single method in the last group is used to fit the contents of the Choice element to the available screen size.
|
As you can see in Figure 1, the List class extends the Screen class. As I mentioned earlier, the List class also implements the Choice interface. Before getting into the details of the List class, I will show you some screen shots of three different types of List objects displayed in the Sun cell phone emulator. I will also show you the standard output produced by the MIDlet named List01 in conjunction with each of the screen shots.
An implicit List object
Figure 3 shows an implicit List object. Note that the element with the string "Two" is highlighted in the list. To highlight an element in the list, navigate to the element using the up and down arrow keys on the emulator keypad (also see the sidebar).
Figure 3. An implicit List object in the cell phone emulator.
The corresponding standard output
Figure 4 shows a partial listing of the standard output for the implicit List object shown in Figure 3. You will learn more about how this output was produced later in conjunction with the discussion of the code for the MIDlet named List01. For now, simply note the one line of text in Figure 4 that was manually highlighted in boldface for presentation in this lesson.
Figure 4. Partial standard output for List01 and an implicit List object.
OUT: Construct MIDlet OUT: Construct Image objects OUT: Create List OUT: Populate list OUT: Display list OUT: Identify selected elements OUT: Selected: Two OUT: Destroy MIDlet |
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
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:
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.
|
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:
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:
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
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.
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.
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.
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.
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 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
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.
Keywords
java J2ME MIDlet "cell phone emulator" "wireless toolkit" WTK MIDP CLDC
Displayable TextBox Ticker TextField Alerts Images Timers Gauges Lists
-end-