gpt4 book ai didi

java - JList - 选择多个项目

转载 作者:太空狗 更新时间:2023-10-29 22:45:50 24 4
gpt4 key购买 nike

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

 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

最佳答案

在调用 JList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) 之后使用 JList.setSelectedIndices(int[])

例如

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

关于java - JList - 选择多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com