我有一个ListView
我正在努力添加一个ContextMenu
到。我有ContextMenu
工作发现但有另一个问题。
My 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;
});
My ListView
可以通过a进行搜索TextField
与听众;侦听器过滤中的项目ListView
当用户输入时。
现在的问题是,当列表被过滤时,任何空单元格现在都会显示null
.
从阅读另一本question https://stackoverflow.com/questions/25286355/removing-items-from-listview-strange-behaviour,我相当有信心ListView
仍然显示已删除单元格的图形。我知道如何通过重写来处理 ListView 中的问题updateItem
方法,但是我将如何从我的内部处理这个问题setCellFactory
方法代替?
这是否可能,或者我需要重构我的整个ListView
?
一如既往地感谢您的帮助!
问题出在线路上
cell.textProperty().bind(cell.itemProperty().asString());
当单元格为空时,该项目将为空,因此绑定将(我相信)评估为字符串"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()));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)