我想在我的vaadin ui中定义TwinColSelect中所选项目的最大数量。我怎样才能实现它。我想让用户只选择4个可用的行星8.我当前的代码是
TwinColSelect table = new TwinColSelect();
table.setImmediate(true);
String planets[] = {"Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune"};
for (int pl=0; pl<planets.length; pl++)
table.addItem(planets[pl]);
table.addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
/*String [] arr=(String [] )event.getProperty().getValue();
if(arr.length>=4){
return;
}*/
}
});
答案 0 :(得分:2)
您可以通过更改选择的值来实现类似的内容:
//Constant declared somewhere in the class
private static final int SELECTED_ITEMS_LIMIT = 4;
...
table.addListener(new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Collection selectedItems = (Collection) event.getProperty().getValue();
if(selectedItems.size()>SELECTED_ITEMS_LIMIT) { //Set no more than SELECTED_ITEMS_LIMIT values
Set<String> noMoreThanLimitItems = new HashSet<String>(selectedItems.size());
int counter = 0;
for(Object item : selectedItems) {
if(counter>=SELECTED_ITEMS_LIMIT) {
break;
}
noMoreThanLimitItems.add((String) item);
counter++;
}
event.getProperty().setValue(noMoreThanLimitItems);
}
}
});
<强>缺点:强>
Property.setValue
点火ValueChangeEvent
。因此,每当用户尝试选择四个以上的行星时,处理代码将被执行两次答案 1 :(得分:1)
提前感谢默认语言环境。昨天我对上面的代码做了一些修改,删除了另一个答案中提到的第一个缺点,并改变了破旧的添加。
Vaadin 7的答案如下:
table.addValueChangeListener(new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Collection selectedItems = (Collection) event.getProperty().getValue();
if(selectedItems.size()>SELECTED_ITEMS_LIMIT) { //Set no more than SELECTED_ITEMS_LIMIT values
Set<String> noMoreThanLimitItems = new HashSet<String>(selectedItems.size());
int counter = 0;
for(Object item : selectedItems) {
if(counter>=SELECTED_ITEMS_LIMIT) {
break;
}
noMoreThanLimitItems.add((String) item);
counter++;
}
event.getProperty().setValue(noMoreThanLimitItems);
//cast to twincol to get the needed functions
//markasdirty makes the object be repainted, so you wil not see more then 4 selected
((TwinColSelect)event.getProperty()).markasdirty();
}
}
});