Java填充组合框
我想用Java填充ComboBox,但是:Java填充组合框,java,arrays,combobox,Java,Arrays,Combobox,我想用Java填充ComboBox,但是: 当我使用字符串数组时,我必须先定义数组的大小(这是缺点) 当我想使用ArrayList时,我不能有空值项或跳过ID: ArrayList a=新的ArrayList(); a、 添加(0,“哈哈”); a、 添加(1,“Bleeee”); a、 增加第(5)款,“克莱伊”)//这会产生一个错误,当我将索引更改为2时,它会工作 JComboBox supplierComboBox=新的JComboBox(a.toArray()); 例如,我的数组是
- 当我使用字符串数组时,我必须先定义数组的大小(这是缺点)
- 当我想使用ArrayList时,我不能有空值项或跳过ID:
ArrayList a=新的ArrayList();
a、 添加(0,“哈哈”);
a、 添加(1,“Bleeee”);
a、 增加第(5)款,“克莱伊”)//这会产生一个错误,当我将索引更改为2时,它会工作
JComboBox supplierComboBox=新的JComboBox(a.toArray());
例如,我的数组是:
[1]=>“狗”,
[5] =>“鼠标”,
[8] =>“猫”。
(缺少一些ID)。
THX.如果没有索引2、3和4,就不能有索引5。Java要么抛出异常,要么用
null
值静默地填充所有跳过的索引。所以只需在2、3和4处添加值,就可以了。确保没有其他跳过的索引
要删除列表中的所有空值,请尝试以下代码:
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();
}
}
公共类RemoveNullValues{
private ArrayList test=new ArrayList();
公共RemoveNullValues(){
测试。添加(“0”);
test.add(null);
测试。添加(“1”);
test.add(null);
test.add(null);
测试。添加(“2”);
测试。添加(“3”);
测试。添加(“4”);
test.add(null);
测试。添加(“5”);
System.out.println(“之前:+测试);
//Java 7及以下方法:
test.removeAll(Collections.singleton(null));
//Java 8+方法:
test.removeIf(Objects::isNull);
System.out.println(“之后:”+测试);
}
公共静态void main(字符串[]args){
新的RemoveNullValues();
}
}
您可以实例化没有子项的组合框
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"
}
然后:
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);
}
ArrayList a=新的ArrayList();
a、 添加(新MyClass(0,“哈哈”);
a、 增加(新MyClass(1,“Bleeee”);
a、 增加(新MyClass(5,“Cleeee”);
for(MyClass值:a){
supplierComboBox.addItem(值);
}
为什么不发布代码?谢谢你的回答。我试过了,它是真实的。但是当我从数据库中加载项目时,一些项目被删除了,然后一些ID丢失了:-(…这就是我不能使用Arraylist的原因。或者我必须自定义它,但我不知道怎么做。@steelbull我编辑了我的答案并添加了一个删除空值的解决方案。是的,但是ID将是0,1,2,我需要0,1,5(如示例中所示)。我需要正确的id。因此,add方法不适用于我的情况。:-(您可以使用对象(具有“id”和“值”等2个属性)或Map.entry。
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);
}