![]() |
The Java Developers Almanac 1.4 |
|
e780. Setting the Selected Items in a JList ComponentList selection events are fired when the following methods are used to change the set of selected items (see e774 Creating a JList Component). // Create a list and get the model
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Select the second item
int start = 1;
int end = 1;
list.setSelectionInterval(start, end); // B
// Select the first 3 items
start = 0;
end = 2;
list.setSelectionInterval(start, end); // A, B, C
// Select all the items
start = 0;
end = list.getModel().getSize()-1;
if (end >= 0) {
list.setSelectionInterval(start, end); // A, B, C, D
}
// Clear all selections
list.clearSelection();
// Select the first item
start = 0;
end = 0;
list.setSelectionInterval(start, end); // A
// Add another selection - the third item
start = 2;
end = 2;
list.addSelectionInterval(start, end); // A, C
// Deselect the first item
start = 0;
end = 0;
list.removeSelectionInterval(start, end); // C
// Select a single item
boolean scrollIntoView = true;
list.setSelectedValue("B", scrollIntoView); // B
e775. Setting the Dimensions of an Item in a JList Component e776. Setting a Tool Tip for an Item in a JList Component e777. Getting the Items in a JList Component e778. Adding and Removing an Item in a JList Component e779. Getting the Selected Items in a JList Component e781. Setting the Selection Mode of a JList Component e782. Arranging Items in a JList Component e783. Detecting Double and Triple Clicks on an Item in a JList Component e784. Listening for Changes to the Selection in a JList Component e785. Listening for Changes to the Items in a JList Component © 2002 Addison-Wesley. |