我的问题很简单。我试图通过单击按钮向Vaadin ComboBox添加一个新项目,该组合已经填充了一些数据。我希望新添加的项目在按钮单击事件处理程序中可用,以便我可以将其添加到数据库表中。
ComboBox region = new ComboBox();
for (RegionDetails details : regions) {
int regionId = details.getRegionId();
String regionName = details.getRegionName();
region.addItem(regionId);
region.setItemCaption(regionId, regionName);
}
Button addR = new Button("Add");
addR.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
// how do I reference the item here?!
}
});
我多次尝试,但没有得到线索。
有人请帮助我。提前谢谢。
答案 0 :(得分:3)
如果您尚未这样做,则应该查看Vaadin书籍/文档中的collecting items in containers章节。由于Vaadin会自动完成大部分工作,因此您的生活更加轻松,因此您无需手动定义字幕,字段等。可能会出现这种情况,但这些情况并不适合,但这些情况很少,并且不在问题的范围内讨论它们。
您可以在下面看到基于您之前的代码和一些虚拟数据的示例。我所做的是使用BeanItemContainer来收集组合的项目数据,并使用他们的 name 属性使Vaadin生成一个标题,而不必手动设置它。此外,在click-listener中,您只需将bean添加到容器中,然后将其保存到DB或您需要执行的任何操作:
public class MyComboBoxComponent extends VerticalLayout {
// bean property to use for caption generation
private static final String CAPTION_PROPERTY = "name";
public MyComboWithItemIDComponent() {
// basic combo instantiation
ComboBox comboBox = new ComboBox();
// use a bean item container
BeanItemContainer<RegionDetails> itemContainer = new BeanItemContainer<>(RegionDetails.class);
comboBox.setContainerDataSource(itemContainer);
// configure the combo to use the "name" property of each item as their caption
// so we don't need to manually set it... magic
comboBox.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
comboBox.setItemCaptionPropertyId(CAPTION_PROPERTY);
// add some dummy data
itemContainer.addAll(generateSomeDummyDetails());
// add button
Button addButton = new Button("Add", event -> {
// create a new bean instance and populate it accordingly
RegionDetails newRegionDetails = new RegionDetails(itemContainer.size(), "Region - " + itemContainer.size());
// add it to the container
itemContainer.addItem(newRegionDetails);
// do whatever you want with the newRegionDetails here
});
// add the components to the layout
addComponent(comboBox);
addComponent(addButton);
}
// method to generate some dummy data
private List<RegionDetails> generateSomeDummyDetails() {
List<RegionDetails> dummyDetails = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dummyDetails.add(new RegionDetails(i, "Region - " + i));
}
return dummyDetails;
}
// the model bean
public class RegionDetails {
private final int id;
private final String name;
public RegionDetails(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
}
结果: