ListSelectionModel
to manage its selection. By default, a list selection model allows any combination of items to be selected at a time. You can specify a different selection mode by calling the setSelectionMode
method on the list. For example, both ListDialog
and ListDemo
set the selection mode to SINGLE_SELECTION
(a constant defined by ListSelectionModel
) so that only one item in the list can be selected. The following table describes the three list selection modes:
Mode Description SINGLE_SELECTION
Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first. SINGLE_INTERVAL_SELECTION
Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first. MULTIPLE_INTERVAL_SELECTION
The default. Any combination of items can be selected. The user must explicitly deselect items.
No matter which selection mode your list uses, the list fires list selection events whenever the selection changes. You can process these events by adding a list selection listener to the list with the addListSelectionListener
method. A list selection listener must implement one method: valueChanged
. Here is the valueChanged
method for the listener in ListDemo
:
Many list selection events can be generated from a single user action such as a mouse click. Thepublic void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
//No selection, disable fire button.
fireButton.setEnabled(false);
} else {
//Selection, enable the fire button.
fireButton.setEnabled(true);
}
}
}
getValueIsAdjusting
method returns true
if the user is still manipulating the selection. This particular program is interested only in the final result of the user's action, so the valueChanged
method does something only if getValueIsAdjusting
returns false
. Because the list is in single-selection mode, this code can use getSelectedIndex
to get the index of the just-selected item. JList
provides other methods for setting or getting the selection when the selection mode allows more than one item to be selected. If you want, you can listen for events on the list's list selection model rather than on the list itself. ListSelectionDemo is an example that shows how to listen for list selection events on the list selection model and lets you change the selection mode of a list dynamically.
Tidak ada komentar:
Posting Komentar