Skip to content

Instantly share code, notes, and snippets.

@apatrida
Last active December 8, 2024 16:24
Show Gist options
  • Save apatrida/370edf7da44e03d6f7d6598457cf743e to your computer and use it in GitHub Desktop.
Save apatrida/370edf7da44e03d6f7d6598457cf743e to your computer and use it in GitHub Desktop.
Setting a JList items to match a source list
// myJList => JList component holding type MyObject
// sourceList => List<MyObject> (or other colleciton type) to match selection
// note MyObject will be checked for referential == if you do not implement equals and hashCode
var model = (DefaultListModel<MyObject>) myJList.getModel();
myJList.clearSelection();
int[] indexes = sourceList.stream()
.mapToInt(obj -> model.indexOf(obj))
.filter(idx -> idx >= 0).toArray();
myJList.setSelectedIndices(indexes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment