steelbull
steelbull

Reputation: 141

Java populate ComboBox

I would like to populate ComboBox in Java, but:

        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());

My array is for example:

[1] => "dog",
[5] => "mouse",
[8] => "cat".
(some ids missing).

THX.

Upvotes: 1

Views: 5158

Answers (2)

ack
ack

Reputation: 1251

You can't have an index of 5 without having indexes of 2, 3, and 4 as well. Java will either throw an exception at this, or it will silently fill all of the skipped indexes with null values. So just add values at 2, 3, and 4 and it should work. Make sure that there are no other skipped indexes as well.

To remove all the null values in a List, try this code:

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();
    }
}

Upvotes: 1

Dante
Dante

Reputation: 106

You can instantiate a combobox without children

JComboBox supplierComboBox = new JComboBox();

and then add the children in a for cycle:

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"
}

Some examples (if you need the id field):

Using 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); 
}

Using MyClass:

public class MyClass{
   private Integer id;
   private String value;

   public MyClass(Integer id, String value) {
       this.id = id;
       this.value= value;
   }

   // Getters & Setters
}

and then:

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); 
}

Upvotes: 0

Related Questions