CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Layout

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);
    }
}
Previous | Summary | Text areas | Scroll panes | Check boxes | Radio buttons | Borders | Combo boxes | Event listeners | Lists | Multiple selections in a list | List models | Next