You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin Flow MultiSelectComboBox无法用鼠标取消选中最后添加的自定义项

Vaadin Flow MultiSelectComboBox自定义项鼠标取消选中异常问题

我基于Vaadin官方示例,用Vaadin Flow(非Lit或React)实现了支持自定义值(开启setAllowCustomValue)的MultiSelectComboBox。目前功能大体正常,但存在一个问题:最后添加的自定义项无法通过鼠标点击取消选中,但用键盘操作可以正常取消。如果新增一个自定义项,之前的倒数第二个自定义项又能正常用鼠标取消选中了。


官方参考代码片段

public ComboBoxCustomEntry2() {
    ComboBox<String> comboBox = new ComboBox<>("Browser");
    comboBox.setAllowCustomValue(true);
    comboBox.addCustomValueSetListener(e -> {
        String customValue = e.getDetail();
        items.add(customValue);
        comboBox.setItems(items);
        comboBox.setValue(customValue);
    });
    add(comboBox);
    comboBox.setItems(items);
    comboBox.setHelperText("Select or type a browser");
}

我的实现代码

LabelComboBox.java

public class LabelComboBox extends MultiSelectComboBox<Label> {

    private Set<Label> availableLabels = new HashSet<>();

    public LabelComboBox(LabelCategoryKey labelCategory) {
        super();
        initLabelSelector();
    }

    private void initLabelSelector() {
        availableLabels = new HashSet<>();
        setWidthFull();
        setLabel(getTranslation("<translation string>"));
        setAllowCustomValue(true);
        setItems(availableLabels);
        setItemLabelGenerator(Label::getLabel);

        addCustomValueSetListener(e -> {
            var customLabel = new Label();
            customLabel.setLabel(e.getDetail());
            availableLabels.add(customLabel);
            // Needed for the items to be selected
            updateSelection(Set.of(customLabel), Collections.emptySet());
            setItemsAndRetainSelectedItems();
            refreshValue();
        });
    }

    // `getValue()` resets `items` but we want to keep it
    private void setItemsAndRetainSelectedItems() {
        var selected = getValue();
        setItems(availableLabels);
        setValue(selected);
    }
}

Label.java

public class Label {
    private Long id;
    private String label;

    // Getter/setters, equals/hashCode elided
}

内容的提问来源于stack exchange,提问作者Guildenstern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:57:05