Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: Clearing the ListView

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);
like image 675
Bade Avatar asked Jun 13 '14 13:06

Bade


People also ask

Is ListView scrollable Javafx?

The ListView class represents a scrollable list of items.

What is a list view in Javafx?

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.


2 Answers

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).

like image 133
James_D Avatar answered Nov 15 '22 10:11

James_D


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

like image 23
user3204934 Avatar answered Nov 15 '22 10:11

user3204934