JList - 选择多个项目

2022-09-02 13:24:41

我遇到了一个问题,当我想自动选择多个值时,它仍然只选择了一个。有没有办法?setSelectedValue()JListJList

 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


答案 1

呼叫 后使用。JList.setSelectedIndices(int[])JList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)

例如

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


答案 2
list.getSelectionModel().setSelectionInterval(...);

或者如果选择不是连续的,则需要使用多个

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

推荐