Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JList - select multiple items

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.

like image 748
Nirav Avatar asked Jun 04 '11 05:06

Nirav


2 Answers

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

like image 52
Andrew Thompson Avatar answered Oct 05 '22 12:10

Andrew Thompson


list.getSelectionModel().setSelectionInterval(...);

or if the selection isn't consecutive then you need to use multiple

list.getSelectionModel().addSelectionInterval(...);
like image 26
camickr Avatar answered Oct 05 '22 13:10

camickr