To return the item selected from a ListView in Java, I would use this code:
listview.getSelectionModel().getSelectedItem();
However, if my ListView allows multiple selection, I can't find a direct way to return all of the items selected in the ListView. Is there a straightforward approach to this?
There is a getSelectedItems() method of the SelectionModel that should do what you want. It returns an observable list - so you can monitor it for changes with a ListChangedLister.
ListView<String> listView = new ListView<>();
ObservableList<String> list = FXCollections.observableArrayList();
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
listView.setItems(list);
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
List<String> selected = listView.getSelectionModel().getSelectedItems();
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