JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines how access
to the list data is achieved. The second model is the ListSelectionModel interface, which
defines methods that determine what list item or items are selected.
Although a JList will work properly by itself, most of the time you will wrap a JList
inside a JScrollPane. This way, long lists will automatically be scrollable, which simplifies
GUI design. It also makes it easy to change the number of entries in a list without having to
change the size of the JList component.
A JList generates a ListSelectionEvent when the user makes or changes a selection.
This event is also generated when the user deselects an item. It is handled by implementing
ListSelectionListener. This listener specifies only one method, called valueChanged( ),
which is shown here:
void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event. Although ListSelectionEvent
does provide some methods of its own, normally you will interrogate the JList object itself
to determine what has occurred. Both ListSelectionEvent and ListSelectionListener are
packaged in javax.swing.event.
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
ListSelectionModel:
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 selection,
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.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home