Reputation: 108
I need to get the last selected item of a ListView which is in MultipleSelectionMode in JavaFX. My code is below but it does not give me the last selected item. It seems to give a random item from the selected items.
addDocumentPagesListView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<PageFile>() {
@Override
public void onChanged(ListChangeListener.Change<? extends PageFile> change) {
while (change.next()) {
if (change.wasAdded()) {
List <? extends PageFile> l = change.getAddedSubList();
Object o = l.get(l.size() - 1);
PageFile pf = (PageFile) o;
System.out.println("Showing pdf file: " + pf.getFile().getName());
}
}
}
});
Upvotes: 1
Views: 2169
Reputation: 108
The code below works, the only problem is that when making a multiple selection two events that are marked as change.wasAdded()
are called for each multiple selection.
if (change.wasAdded()) {
List<? extends PageFile> l = change.getList();
Object o = l.get(l.size() - 1);
if (o != null) {
PageFile pf = (PageFile) o;
System.out.println("Showing pdf file: " + pf.getFile().getName());
}
} else if (change.wasRemoved()) {
List<? extends PageFile> l = change.getList();
Object o = l.get(l.size() - 1);
if (o != null) {
PageFile pf = (PageFile) o;
System.out.println("Showing pdf file: " + pf.getFile().getName());
}
}
Upvotes: 1
Reputation: 328649
You should have a look at the selectedItemProperty
which always points to the last selected item:
The selected item property is most commonly used when the selection model is set to be single selection, but is equally applicable when in multiple selection mode. When in this mode, the selected item will always represent the last selection made.
Upvotes: 2