Java Reference
In-Depth Information
By default, a JList allows the user to select multiple ranges of items within the list, but
you can change this behavior by calling setSelectionMode( ) , which is defined by JList . It
is shown here:
void setSelectionMode(int mode )
Here, mode specifies the selection mode. It must be one of these values defined by the
ListSelectionModel interface (which is packaged in javax.swing ):
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
The default, multiple-interval selection lets the user select multiple ranges of items within
a list. With single-interval selection, the user can select one range of items. With single se-
lection, the user can select only a single item. Of course, a single item can be selected in
the other two modes, too. It's just that they also allow a range to be selected.
You can obtain the index of the first item selected, which will also be the index of
the only selected item when using single-selection mode, by calling getSelectedIndex( ) ,
shown here:
int getSelectedIndex( )
Indexing begins at zero. So, if the first item is selected, this method will return 0. If no item
is selected, -1 is returned.
You can obtain an array containing all selected items by calling getSelectedIndices( ) ,
shown next:
int[ ] getSelectedIndices( )
In the returned array, the indices are ordered from smallest to largest. If a zero-length array
is returned, it means that no items are selected.
The following program demonstrates a simple JList , which holds a list of names. Each
time a name is selected in the list, a ListSelectionEvent is generated, which is handled by
the valueChanged( ) method defined by ListSelectionListener . It responds by obtaining
the index of the selected item and displaying the corresponding name. Sample output is
shown in Figure 16-5 .
Search WWH ::




Custom Search