1

我想在我的 vaadin ui 中定义 TwinColSelect 中选定项目的最大数量。我怎样才能实现它。我想让用户从可用的 8 个行星中只选择 4 个行星。我当前的代码是

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;
        }*/
    }
});
4

2 回答 2

2

您可以通过更改 select 的值来实现类似的功能:

//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.setValueValueChangeEvent。因此,当用户尝试选择超过四个行星时,处理代码将执行两次
于 2013-09-04T11:34:52.117 回答
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();
    }  
}
});
于 2016-05-15T07:34:01.000 回答