我有一个ListView
,我正在努力添加一个ContextMenu
。我有ContextMenu
工作查找,但有另一个问题。
我的setCellFactory
代码,用于设置上下文菜单:
lvAppetites.setCellFactory(lv -> {
ListCell<Appetite> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
MenuItem editAppetiteMenu = new MenuItem();
editAppetiteMenu.textProperty().bind(Bindings.format("Edit ..."));
editAppetiteMenu.setOnAction(event -> {
// Code to load the editor window
editAppetite(cell.getItem());
});
contextMenu.getItems().add(editAppetiteMenu);
MenuItem deleteAppetiteMenu = new MenuItem();
deleteAppetiteMenu.textProperty().bind(Bindings.format("Delete ..."));
deleteAppetiteMenu.setOnAction(event -> {
// Code to delete the appetite
});
contextMenu.getItems().add(deleteAppetiteMenu);
contextMenu.getItems().add(new SeparatorMenuItem());
MenuItem addAppetiteMenu = new MenuItem();
addAppetiteMenu.textProperty().bind(Bindings.format("Add New ..."));
addAppetiteMenu.setOnAction(event -> {
// Code to delete the appetite
});
contextMenu.getItems().add(addAppetiteMenu);
cell.textProperty().bind(cell.itemProperty().asString());
// If nothing selected, remove the context menu
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell;
});
我的ListView
可以通过带有侦听器的TextField
进行搜索;侦听器在用户键入时筛选ListView
中的项目。
现在的问题是,随着列表的过滤,任何空单元格现在都显示为null
。
通过阅读另一个问题,我相当有信心ListView
仍在显示已删除单元格的图形。 我知道如何通过重写updateItem
方法在 ListView 中处理这个问题,但我如何在我的setCellFactory
方法中处理这个问题?
这甚至可能还是我需要重构我的整个ListView
?
一如既往地感谢您的所有帮助!
问题出自
cell.textProperty().bind(cell.itemProperty().asString());
当单元格为空时,该项目将为 null,因此绑定将(我相信(计算为字符串"null"
。
尝试测试单元格是否为空或项目为空的操作,例如
cell.textProperty().bind(Bindings
.when(cell.emptyProperty())
.then("")
.otherwise(cell.itemProperty().asString()));
或(感谢@fabian改进此版本(
cell.textProperty().bind(Bindings.createStringBinding(
() -> Objects.toString(cell.getItem(), ""),
cell.itemProperty()));