我想在Java中填充ComboBox,但是:
ArrayList<String> a = new ArrayList<String>();
a.add(0, "hahah");
a.add(1, "bleeeee");
a.add(5, "cleeeee"); //this makes an error, when I change index to 2, it works
JComboBox supplierComboBox = new JComboBox(a.toArray());
我的数组是例如:
[1] => "dog",
[5] => "mouse",
[8] => "cat".
(some ids missing).
THX。
答案 0 :(得分:1)
如果没有索引2,3和4,则索引不能为5。 Java将在此处抛出异常,或者它将以null
值静默填充所有跳过的索引。所以只需在2,3和4处添加值就可以了。确保没有其他跳过的索引。
要删除List中的所有空值,请尝试以下代码:
public class RemoveNullValues {
private ArrayList<String> test = new ArrayList<String>();
public RemoveNullValues() {
test.add("0");
test.add(null);
test.add("1");
test.add(null);
test.add(null);
test.add("2");
test.add("3");
test.add("4");
test.add(null);
test.add("5");
System.out.println("Before: " + test);
//Java 7 and below method:
test.removeAll(Collections.singleton(null));
//Java 8+ method:
test.removeIf(Objects::isNull);
System.out.println("After: " + test);
}
public static void main(String[] args) {
new RemoveNullValues();
}
}
答案 1 :(得分:0)
您可以实例化没有孩子的组合框
JComboBox supplierComboBox = new JComboBox();
然后在for循环中添加子项:
ArrayList<String> a = new ArrayList<String>();
a.add("hahah");
a.add("bleeeee");
a.add("cleeeee");
for (String value : a) {
supplierComboBox.addItem(value); // you can put every kind of object in "addItem"
}
一些例子(如果你需要id字段):
使用 Map.Entry
ArrayList<Map.Entry<Integer, String>> a = new ArrayList<Map.Entry<Integer, String>>();
a.add(new AbstractMap.SimpleEntry<Integer, String>(0, "hahah"));
a.add(new AbstractMap.SimpleEntry<Integer, String>(1, "bleeeee"));
a.add(new AbstractMap.SimpleEntry<Integer, String>(5, "cleeeee"));
for (Map.Entry<Integer, String> value : a) {
supplierComboBox.addItem(value);
}
使用 MyClass :
public class MyClass{
private Integer id;
private String value;
public MyClass(Integer id, String value) {
this.id = id;
this.value= value;
}
// Getters & Setters
}
然后:
ArrayList<MyClass> a = new ArrayList<MyClass>();
a.add(new MyClass(0, "hahah"));
a.add(new MyClass(1, "bleeeee"));
a.add(new MyClass(5, "cleeeee"));
for (MyClass value : a) {
supplierComboBox.addItem(value);
}