Java Reference
In-Depth Information
Instead of returning the actual
Object
, its index (as computed by the order of
calls to
addItem
) can be returned by calling
getSelectedIndex
. The first item
added has index 0, and so on. This can be useful because if an array stores
information corresponding to each of the choices,
getSelectedIndex
can be
used to index this array. The
setSelectedIndex
method is used to specify a
default selection.
JList
The
JList
component allows the selection from a scrolling list of
Object
s. In
Figure B.1, the choice of colors is presented as a
JList
. The
JList
differs from
the
JComboBox
in three fundamental ways:
The
JList
compo-
nent allows the
selection from a
scrolling list of
Object
s. It can be
set up to allow for
either one selected
item or multiple
selected items.
1.
The
JList
can be set up to allow either one selected item or
multiple selected items (the default is multiple selection).
2.
The
JList
allows the user to see more than one choice at a time.
3.
The
JList
will take up more screen real estate than the
Choice
.
The basic
JList
methods are
JList( );
JList( Object [ ] items );
void setListData( Object [ ] items );
int getSelectedIndex( );
int [ ] getSelectedIndices( );
Object getSelectedValue( );
Object [ ] getSelectedValues( );
void setSelectedIndex( int index );
void setSelectedValue( Object value );
void setSelectionMode( int mode );
A
JList
is constructed with either no parameters or an array of items
(there are other constructors that are more sophisticated). Most of the listed
methods have the same behavior (with possibly different names) as the corre-
sponding methods in
JComboxBox
.
getSelectedValue
returns
null
if no items are
selected.
getSelectedValues
is used to handle multiple selection; it returns an
array of
Object
s (possibly length 0) corresponding to the selected items. As
with the
JComboxBox
, indices instead of
Object
s can be obtained by other public
methods.
setSelectionMode
is used to allow only single-item selection. The boiler-
plate code is
lst.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
Search WWH ::
Custom Search