returns the index of the item. The first item is at index 0. If more than one item is selected, or if
no selection has yet been made, ­1 is returned.
For lists that allow multiple selection, you must use either getSelectedItems( ) or
getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected items.
getSelectedIndexes( ) returns an array containing the indexes of the currently selected items.
To obtain the number of items in the list, call getItemCount( ). You can set the currently
selected item by using the select( ) method with a zero-based integer index. These methods
are shown here:
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Lists
To process list events, you will need to implement the ActionListener interface. Each time
a List item is double-clicked, an ActionEvent object is generated. Its getActionCommand( )
method can be used to retrieve the name of the newly selected item. Also, each time an item is
selected or deselected with a single click, an ItemEvent object is generated. Its getStateChange( )
method can be used to determine whether a selection or deselection triggered this event.
getItemSelectable( ) returns a reference to the object that triggered this event.
Here is an example that converts the Choice controls in the preceding section into List
components, one multiple choice and the other single choice:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home