Controls and layout managers
Components
Multiple selections in a list
A list that allows multiple selections
Fields of the ListSelectionModel interface used to set the selection mode
Field | Description |
---|---|
SINGLE_SELECTION | Allows just one selection. |
SINGLE_INTERVAL_SELECTION | Allows a single range of selections. |
MULTIPLE_INTERVAL_SELECTION | Allows multiple ranges of selections. This is the default. |
Methods of the JList class used to process multiple selections
Method | Description |
---|---|
getSelectedValues() | Returns an array of Object types for the selected items. |
getSelectedIndices() | Returns an array of ints corresponding to the indices of the selected items. |
Code that creates a list
descriptions = getProductDescriptions(); // returns an array of descriptions
productList = new JList(descriptions);
productList.setFixedCellWidth(200);
productList.setVisibleRowCount(5);
productList.setSelectedIndex(0);
productList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(productList));
Code that displays the list selections
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == acceptButton) { Object[] selections = productList.getSelectedValues(); String s = ""; for (Object o : selections) s += (String)o + "\n"; productTextArea.setText("You selected:\n" + s); } }