我一直试图删除javafx列表视图中除选定项目以外的所有项目。我写了下面的代码。它有时有效,有时无效。我无法弄清楚我的错误。任何帮助将不胜感激!
try {
int i = 0;
while (!listName.getItems().equals(listName.getSelectionModel().getSelectedItems())) {
if (listName.getSelectionModel().isSelected(i) == false) {
listName.getItems().remove(i);
i--;
}
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
您可以获取选定的项,将它们放入ObservableList
中,然后可以像这样从Java8使用removeIf
:
ObservableList<String> selectedItems = listName.getSelectionModel().getSelectedItems();
listName.getItems().removeIf(item -> !selectedItems.contains(item));
答案 1 :(得分:0)
您可以简单地创建一组要保留的项目,并使用ObservableList.setAll
替换整个列表:
ListView<Character> listView = new ListView<>();
for (char c = 'a'; c <= 'z'; c++) {
listView.getItems().add(c);
}
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Button delete = new Button("delete");
delete.setOnAction(evt -> {
Character[] selection = listView.getSelectionModel()
.getSelectedIndices()
.stream()
.sorted()
.map(listView.getItems()::get)
.toArray(Character[]::new);
listView.getItems().setAll(selection);
listView.getSelectionModel().selectAll();
});