我有一个使用自定义对象填充的ComboBox
。然而,我需要允许选择无选择(或空值)。我尝试过comboBox.getItems().add(null)
,但这不会添加空选项。
如何在顶部添加一个空白选项,以实现允许用户“取消选中”所有项目的功能?
您可以添加一个占位符元素。而不是检查未选中的项目,您只需要测试引用相等性。根据类设计,您可能需要使用自定义单元格工厂来显示此项无文本:
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));