简体   繁体   English

如何将“空”选择添加到ComboBox?

[英]How to add “empty” selection to ComboBox?

I have a ComboBox populated with a custom object. 我有一个填充有自定义对象的ComboBox However, I need to allow the selection of no selection (or a null value). 但是,我需要允许没有选择(或空值)的选择。 I have tried comboBox.getItems().add(null) but that does not add an empty selection. 我已经试过comboBox.getItems().add(null)但是不会添加空选择。

How do I add a blank selection at the top to essentially allow a user to "deselect" all items? 如何在顶部添加空白选择,以实质上允许用户“取消选择”所有项目?

You could add a placeholder element. 您可以添加一个占位符元素。 Instead of checking for deselected items you simply need to test reference equality. 无需检查取消选择的项目,您只需要测试引用的相等性即可。 Depending on the class design you may need to use a custom cell factory to display the no text for this item: 根据类设计,您可能需要使用自定义单元工厂来显示此项目的无文本:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM