I want to clear all content from the ListView when I click on some button. I was trying to remove it by indices but it was giving me exceptions. I don't quite get the SelectionModel of ListView. Here are my attempts:
asiLogsListView.getSelectionModel().selectAll();
ObservableList<Integer> indices = asiLogsListView.getSelectionModel().getSelectedIndices();
for(int index : indices) {
asiLogsListView.getSelectionModel().getSelectedItems().remove(index);
}
or
asiLogsListView.getSelectionModel().getSelectedItems().removeAll(indices);
The ListView class represents a scrollable list of items.
A ListView displays a horizontal or vertical list of items from which the user may select, or with which the user may interact. A ListView is able to have its generic type set to represent the type of data in the backing model.
To clear all the items from a ListView
, just do
asiLogsListView.getItems().clear();
If you want to clear the selection, then do
asiLogsListView.getSelectionModel().clearSelection();
The tricky one is removing all the selected items from the ListView
:
List<Integer> selectedItemsCopy = new ArrayList<>(asiLogsListView.getSelectionModel().getSelectedItems());
asiLogsListView.getItems().removeAll(selectedItemsCopy);
Your code looks like it is trying to clear the selection, because you are trying to remove all the elements from the selectionModel
's selectedItems
list. The problem is that as you remove each item, the index of the remaining items would change, so you end up removing the wrong items, and potentially may end up with ArrayIndexOutOfBoundsException
s (if you end up with fewer items than the largest index of a selected item).
The original problem is next: ListView.getSelectionMode() returns part of it's observable list but not the copy. So removing from that list leads to various issues.
Use next code which copies list before removing items from it:
sendRightButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
ObservableList<String> potential =
FXCollections.observableArrayList( //copy
candidatesListView.getSelectionModel().getSelectedItems());
if (potential != null) {
heroes.addAll(potential);
candidates.removeAll(potential);
candidatesListView.getSelectionModel().clearSelection();
}
}
});
For more detail : http://javafx-jira.kenai.com/browse/RT-24367
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With