如果您将 ComboBox 用作即时并且不希望将“Person:”作为真人处理,则可以使用setNullSelectionItemId
将假人定义为真正的虚拟对象。但是,此解决方案有一个限制,即您只能添加一个虚拟对象。
这是我的示例,它在列表顶部添加“Person:”并将其作为空值处理。请注意,我使用的是 Vaadin 7。
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
/**
* The Application's "main" class
*/
@SuppressWarnings("serial")
public class MyVaadinUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
BeanItemContainer<Person> container = new BeanItemContainer<Person>(Person.class);
Person nullPerson = new Person(0, "Person:");
container.addBean(nullPerson);
container.addBean(new Person(1, "Django"));
container.addBean(new Person(2, "Schultz"));
ComboBox combobox = new ComboBox();
combobox.setImmediate(true);
combobox.setNullSelectionItemId(nullPerson); // Define the null person as a dummy.
combobox.setContainerDataSource(container);
combobox.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
combobox.setItemCaptionPropertyId("name"); // the person's name field will be shown on the UI
combobox.addValueChangeListener(new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
// Will display 'null selected' when nullPerson is selected.
Notification.show(event.getProperty().getValue() + " selected");
}
});
layout.addComponent(combobox);
}
}