other

Senin, 01 Desember 2008

Selecting Items in a List

A list uses an instance of 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:

ModeDescription
SINGLE_SELECTION
Single selection means only one item can be selected at once

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
Single interval selection means multiple, contiguous items can be selected at once

Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first.
MULTIPLE_INTERVAL_SELECTION
Multiple interval selection means any combination of items can be selected at once

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:

public 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);
}
}
}
Many list selection events can be generated from a single user action such as a mouse click. The 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:

other