当我想在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
已选中。
答案 0 :(得分:13)
致电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));
}
});
}
}
答案 1 :(得分:4)
list.getSelectionModel().setSelectionInterval(...);
如果选择不连续,则需要使用多个
list.getSelectionModel().addSelectionInterval(...);
答案 2 :(得分:4)
在使用NetBeans GUI编辑器时,您可以自定义为Post-Creation Code
生成的JList
,如下所示。
答案 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));
}
});
}
}