JList - 选择多个项目

时间:2011-06-04 05:18:21

标签: java swing netbeans jlist multi-select

当我想在setSelectedValue()中自动选择多个值时,我在JList中遇到了这个JList方法的问题,它仍然只选择了一个。有办法吗?

 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);

此代码仅显示Item 2已选中。

4 个答案:

答案 0 :(得分:13)

致电JList.setSelectedIndices(int[])后使用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 of code

答案 1 :(得分:4)

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

如果选择不连续,则需要使用多个

list.getSelectionModel().addSelectionInterval(...);

答案 2 :(得分:4)

在使用NetBeans GUI编辑器时,您可以自定义为Post-Creation Code生成的JList,如下所示。

post-creation dialog

答案 3 :(得分:0)

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));
            }
        });
    }
}