Search code examples
javaframeworksvaadinvaadin7

Populate ComboBox with HashMap?


I'm trying populate a combobox of vaadin7 with informations hashmap. I create a class that return a HashMap when I get the return I use a for each to populate this combobox but does show me only numbers and not the keys and values of hashmap.

I'm trying this.

/** states of brasil class */
public class EstadosBrasil {
private static final HashMap<String, String> uf = new HashMap();

/** return all states of brasil */
public static HashMap<String, String> getEstados(){             
    uf.put("AC", "AC");
    uf.put("AL", "AL");
    uf.put("AM", "AM");
    uf.put("AP", "AP");
    uf.put("BA", "BA");
    uf.put("CE", "CE");
    uf.put("DF", "DF");
    uf.put("ES", "ES");
    uf.put("FN", "FN");
    uf.put("GO", "GO");
    uf.put("MA", "MA");
    uf.put("MG", "MG");
    uf.put("MS", "MS");
    uf.put("MT", "MT");
    uf.put("PA", "PA");
    uf.put("PB", "PB");
    uf.put("PE", "PE");
    uf.put("PI", "PI");
    uf.put("PR", "PR");
    uf.put("RJ", "RJ");
    uf.put("RN", "RN");
    uf.put("RO", "RO");
    uf.put("RR", "RR");
    uf.put("RS", "RS");
    uf.put("SC", "SC");
    uf.put("SE", "SE");     
    uf.put("SP", "SP");
    uf.put("TO", "TO");

    return uf;
}   

}

// my combobox 
private ComboBox comboEstado;
comboEstado = new ComboBox("States");
comboEstado.setWidth("100px");
HashMap<String, String> estados = EstadosBrasil.getEstados();       
for(Entry<String, String> e : estados.entrySet()){                  
    Object obj = comboEstado.addItem();
    comboEstado.setItemCaption(e.getKey(), e.getValue());           
    comboEstado.setValue(obj);
}
mainLayout.addComponent(comboEstado);

Any idea ?

thanks


Solution

  • Change-

    Object obj = comboEstado.addItem();
    comboEstado.setItemCaption(e.getKey(), e.getValue());           
    comboEstado.setValue(obj);
    

    To-

    comboEstado.addItem(e.getKey());
    comboEstado.setItemCaption(e.getKey(), e.getValue()); 
    

    If you want both key and value pair to appear, something like this can be done-

    comboEstado.setItemCaption(e.getKey(), e.getKey() + " : " +  e.getValue());
    

    By the way, I hope you are going to change the values. If both key and value are the same, you can just use a Set.