Wicket DropDownChoice中的分隔符

时间:2011-07-06 07:24:00

标签: java drop-down-menu wicket

是否有一些明显的方法可以将分隔符添加到Wicket DropDownChoice中的选项列表中?在我的情况下,我用我的数据源中的两种类型的域对象填充选择。我想我可以手动将某种虚拟域对象添加到选项列表中,但感觉非常难看。

示例:

+---------+-+
| Apple   |▼|
| Orange  +-+
| ------- |
| Carrot  |
| Cucumber|
+---------+

当前代码(没有任何分隔符)类似于:

EntityModel model = getModel();
List<? extends Produce> foods = foodService.getAllProduce(); 
// getAllProduce() returns first all fruits, then all vegetables
add(new DropDownChoice<Produce>(
    "produceSelect", new PropertyModel<Produce>(model, "favProduce"), foods)
);

3 个答案:

答案 0 :(得分:7)

我最终使用了来自wicket-extensionsSelectSelectOptions组件来解决这个问题,正如martin-g所述。

SelectOptions<Produce> fruitOptions = new SelectOptions<Produce>(
                                      "fruits",
                                      fruitCollection, 
                                      new FruitRenderer());

SelectOptions<Produce> vegetableOptions = new SelectOptions<Produce>(
                                          "vegetables",
                                          vegetableCollection, 
                                          new VegetableRenderer());

Select select = new Select("produceSelect", 
                           new PropertyModel<Produce>(model, "favProduce"));
select.add(fruitOptions);
select.add(vegetableOptions);

相应的HTML看起来像这样:

<select wicket:id="produceSelect" id="produceSelect">
    <optgroup label="Fruits">
        <wicket:container wicket:id="fruits">
            <option wicket:id="option">Apple</option>
        </wicket:container>
    </optgroup>
    <optgroup label="Vegetables">
        <wicket:container wicket:id="vegetables">
            <option wicket:id="option">Carrot</option>
        </wicket:container>
    </optgroup>
</select>

由于optgroup标签以粗体显示且无法选择,因此会产生稍微不同但效果更好的结果:

+----------------+-+
| **Fruits**     |▼|
| Apple          +-+  
| Orange         | 
| **Vegetables** |  
| Carrot         |
| Cucumber       |
+----------------+

答案 1 :(得分:5)

    add(new DropDownChoice<String>("choice", Arrays.asList("Apple","Orange","Carrot","Cucumber")) {
        @Override
        protected void appendOptionHtml(AppendingStringBuffer buffer, String choice, int index, String selected) {
            super.appendOptionHtml(buffer, choice, index, selected);
            if ("Orange".equals(choice)) {
                buffer.append("<optgroup label='----------'></optgroup>");
            }
        }
    });

答案 2 :(得分:2)