简体   繁体   中英

Vaadin: How do I add options to a combo box?

I have a combo box that I am trying to add options to. How Do I go about this? This is what I have so far:

ComboBox contactPrefixNametf = new ComboBox("Prefix");
contactPrefixNametf.setItemCaption(contactPrefixNametf, "Mr");
fLayout.addComponent(contactPrefixNametf);
contactPrefixNametf.setImmediate(true);

I guess .setItemCaption() is not the correct method? What is the correct method?

Thank you in advance!

Use addItem() method:

    final ComboBox my_combox_box = new ComboBox("My Combo Box");
    for (final My_object mo: list_of_my_objects)
    {
        my_combox_box.addItem(mo);
        my_combox_box.setItemCaption(mo, mo.name());
    }

This example uses addItem inconjunction with setItemCaption() to store the actual object selected by the user with a display friendly name (if toString() is not appropriate).

myComboBox.addItem("Option 1");

(Especially if you are new to Vaadin), I suggest to try Viritin add-on and its TypedSelect variant of ComboBox. Its well typed API makes many things ridiculously simpler. For instance it has a (typed) setOptions method and its value change listeners provide the value directly instead of through untyped Property interface.

A code example of its usage:

List<Person> options = service.findMyPersons();

TypedSelect<Person> select = new TypedSelect<>(Person.class)
        .withSelectType(ComboBox.class);
select.setOptions(options);
// If toString() representation is not good, modify it to something else
select.setCaptionGenerator(person -> person.getFirstName() + person.getLastName());

select.addMValueChangeListener(event -> {
    Person person = event.getValue();
});

Disclaimer: I'm the maintainer of Viritin, but also have maintained Vaadin for 8 years and nowadays work as its developer advocate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM