JList - 选择多个项目 [英] JList - select multiple items
本文介绍了JList - 选择多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 JList
中遇到这个 setSelectedValue()
方法的问题,当我想在a中选择多个值时 JList
自动,它仍然只选择一个。有办法吗?
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);
此代码仅显示第2项
已选中。
推荐答案
调用后使用 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
这篇关于JList - 选择多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文