【发布时间】:2018-11-15 19:09:02
【问题描述】:
我在我的项目中使用 ListView,并希望为每个列表项添加一个上下文菜单,以便可以单独删除每个列表项。使用以下代码时,这似乎工作得很好:
postList.setCellFactory(lv -> {
ListCell<Result> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
@Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
cell.textProperty().bind(stringBinding);
MenuItem deleteItem = new MenuItem();
deleteItem.textProperty().bind(Bindings.format("Delete item"));
deleteItem.setOnAction(event -> postList.getItems().remove(cell.getItem()));
contextMenu.getItems().addAll(openPermalink, openSubreddit, openURL, deleteItem);
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell;
});
但是,在清除帖子列表后 - 尽管项目似乎已被删除 - 当添加另一个时,所有已删除的项目都会重新出现,并且要添加的项目不会显示。
任何可能导致此问题的项目?只有在我设置单元工厂时才会发生这种情况,否则就可以了。
谢谢!
编辑:看来问题主要与此段有关
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
@Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
看起来,即使项目在那里,它们的显示标题也是空的
【问题讨论】:
-
我使用的代码是从那里改编的,但问题完全不同
-
您在代码中做了哪些不同的事情? How to create a Minimal, Complete, and Verifiable example.
-
我已经编辑了这篇文章,并进行了一些进一步的探索,并将问题缩小到特定的 sn-p