Ferre12
Ferre12

Reputation: 1303

Event listener for multiple selection in a JavaFx listview

I have a JavaFX listview in my code and multiple items can be selected. I have already figured out which event listener I need to use when an item is selected but this listener isn't always triggered when i deselect an item. So my question is, is there an event listener for both selecting and deselecting items?

This is the event listener I'm currently using:

lvLijst.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue)
        {
            //code
        }
    });

Thanks in advance.

Upvotes: 0

Views: 2255

Answers (1)

James_D
James_D

Reputation: 209694

You need to listen to the list of selected items, not the single selected item. When you have multiple selection enabled, the selectedItemProperty() will always refer to the last (in time) item selected when multiple items are selected. This property will not always change when the list changes - specifically if you deselect any item other than the last one selected, so your listener will not be notified for every change to the list.

Instead, do

lvLijst.getSelectionModel().getSelectedItems().addListener((Change<? extends String> c) -> {
    // code ...
});

Upvotes: 3

Related Questions