【问题标题】:ListView CellFactory - How to remove cells correctly?ListView CellFactory - 如何正确删除单元格?
【发布时间】:2017-07-31 18:15:25
【问题描述】:

我有一个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

通过阅读另一个question,我相当有信心ListView 仍在显示已删除单元格的图形。我知道如何通过覆盖 updateItem 方法在 ListView 中处理这个问题,但是我将如何在我的 setCellFactory 方法中处理这个问题?

这是否可能,或者我需要重构我的整个ListView

一如既往地感谢您的帮助!

【问题讨论】:

  • 为什么不在updateItem 代码中处理支持列表单元格的项目的更新(包括项目删除,因为它们也注册为更新),而不是尝试在单元格工厂中内联?覆盖 updateItem 并处理任何逻辑将有“标准”方式来完成此操作,而不是通过绑定和侦听器。

标签: listview javafx listviewitem


【解决方案1】:

问题出在线路

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

【讨论】:

  • 谢谢@James_D,一如既往。我以前从未见过when/then/otherwise 范式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多