Java Reference
In-Depth Information
Figure 13-8.
Visual representation of selection modes
To change the selection mode of a
JList
, set its
selectionMode
property to one of the
ListSelectionModel
constants shown in Table 13-6. For instance, the following would change
a list to single-selection mode:
JList list = new JList(...);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
The
DefaultListSelectionModel
class is the default implementation of the
ListSelectionModel
interface. You can examine any of its nine properties, shown in
Table 13-7, to learn about the currently selected range.
Table 13-7.
DefaultListSelectionModel Properties
Property Name
Data Type
Access
anchorSelectionIndex
int
Read-write
leadAnchorNotificationEnabled
boolean
Read-write
leadSelectionIndex
int
Read-write
listSelectionListeners
ListSelectionListener[ ]
Read-only
maxSelectionIndex
int
Read-only
minSelectionIndex
int
Read-only
selectionEmpty
boolean
Read-only
selectionMode
int
Read-write
valueIsAdjusting
boolean
Read-write
The selection model can show you what is currently being used in the multiple-selection
mode when the
selectionEmpty
property is
false
. Simply ask each index between the minimum
and maximum selection indices if it's selected with
public boolean isSelectedIndex(int index)
.
Because multiple-selection mode supports noncontiguous areas, this is the only way to find
out what's selected. However, the
selectedIndices
property of
JList
provides this information
without you needing to check it manually.