why_vincent
why_vincent

Reputation: 2262

How to iterate through ComboBox in Vaadin?

I am working with Vaadin and I have some trouble iterating through choices in a ComboBox. I have my object looking like:

class MyObject{
    private String text;
    private Integer i;
    public MyObject(String text,Integer i){
        this.text = text;
        this.i = i;
    }
    public String toString(){
        return text;
    }
    //Getters and setters omitted
}

I add it to the box like this:

MyObject o1 = new MyObject("o1",23);
MyObject o2 = new MyObject("o2",44);
ComboBox box=new ComboBox();
box.addItem(o1);
box.addItem(o2);

This works great when I want to get the chosen data:

MyObject o3 = (MyObject)box.getValue();

But now I need to iterate through the choices in the ComboBox and I don't know how. I seem to need some kind of ID but I don't know how to use that. I tried the following with no success but it doesn't work(and is really ugly):

Collection IDs = box.getItemIds();
Iterator it = IDs.iterator();
while(it.hasNext()){
    Object id = it.next();
    Item item = IDs.getItem(id);
    //What to do now?
}

I'd like to keep my object simple and avoid using beans and complex containers. Vaadins examples are mostly for String and that doesn't help me so much. I'd really appreciate any help.

Upvotes: 2

Views: 3633

Answers (1)

Charles Anthony
Charles Anthony

Reputation: 3155

If you look at the javadoc for ComboBox, you'll see that the addItem method is actually defined on the AbstractSelect class, and it actually takes the itemId as the parameter. (This is in turn delegated to the Select's container, which in this default case is an IndexedContainer)

So, Collection IDs=box.getItemIds(); will return you the collection of MyObject - i.e. what you are actually after.

Upvotes: 5

Related Questions