JavaFX: Clearing the ListView


Question

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);
1
4
1/10/2017 3:20:03 AM

Accepted Answer

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 ArrayIndexOutOfBoundsExceptions (if you end up with fewer items than the largest index of a selected item).

12
6/13/2014 7:04:19 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon