JList - select multiple items

Nirav picture Nirav · Jun 4, 2011 · Viewed 46.5k times · Source

I faced a problem with this setSelectedValue() method in JList when I wanted to select multiple values in a JList automatically, it still selected only one. Is there a way?

 String[] items = { "Item 1", "Item 2", "Item 3", "Item 4" };
      final JList theList = new JList(items);
      theList.setSelectedValue("Item 1",true);
      theList.setSelectedValue("Item 2",true);

This code shows only Item 2 as selected.

Answer

Andrew Thompson picture Andrew Thompson · Jun 4, 2011

Use JList.setSelectedIndices(int[]) after calling JList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION).

E.G.

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
class MultiSelectList {
    public static void main(String[] args) throws Exception {
        File f = new File("MultiSelectList.java");
        InputStream is = new FileInputStream(f);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        final ArrayList<String> lines = new ArrayList<String>();
        String line = br.readLine();
        while (line!=null) {
            lines.add(line);
            line = br.readLine();
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JList list = new JList(lines.toArray());
                list.setSelectionMode(
                    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                int[] select = {19, 20, 22};
                list.setSelectedIndices(select);
                JOptionPane.showMessageDialog(null, new JScrollPane(list));
            }
        });
    }
}

Screen Shot

Screen shot of code