如何在ComboBox中添加“空”选项?

3

我有一个使用自定义对象填充的ComboBox。然而,我需要允许选择选择(或空值)。我尝试过comboBox.getItems().add(null),但这不会添加空选项。

如何在顶部添加一个空白选项,以实现允许用户“取消选中”所有项目的功能?

1个回答

4

您可以添加一个占位符元素。而不是检查未选中的项目,您只需要测试引用相等性。根据类设计,您可能需要使用自定义单元格工厂来显示此项无文本:

public class CustomItem {

    private final String text;

    public CustomItem(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

}

final CustomItem emptyPlaceholder = new CustomItem(null);
ComboBox<CustomItem> combo = new ComboBox<>();
combo.getItems().addAll(emptyPlaceholder, new CustomItem("foo"), new CustomItem("bar"));
combo.setCellFactory(lv -> new ListCell<CustomItem>() {

    @Override
    protected void updateItem(CustomItem item, boolean empty) {
        super.updateItem(item, empty);

        setText((empty || item == null || item == emptyPlaceholder)
                ? ""
                : item.getText());
    }

});
combo.setButtonCell(combo.getCellFactory().call(null));

不必使用占位符元素,您可以创建一个额外的列表,其中包含null作为第一项,并根据原始列表进行更新:https://stackoverflow.com/a/60580431/898747 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接