Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple selected items from a JList

Tags:

java

swing

jlist

I am creating a screen with four lists on it. Basically two pairs of lists where you can select lines on one list in the pair and move them to the other list in the pair.

Looking at the documentation I need a ListSelectionModel for each list to determine which lines have been selected. I will use a [Sel] or [Des] button to do the actual transfer.

sample screen

The documentations and samples say I need a ListSelectionListener but as I will not access the model until the user clicks on the button do I actually need a listener? Will the model still have the getMinSelectionIndex, getMaxSelectionIndex and isSelectedIndex set if I do not have a listener?


1 Answers

You do not need a listener, a listener is only useful for keeping something in sync elsewhere, which you don't need.

You can access the selected indexes at any point after the selection event(s) occurs. The method JList.getSelectedIndices returns an array of currently selected indexes, and getSelectedValuesList() returns the actual items depending on what you want....

JList<String> items = new JList<String>(new String[] { "foo", "bar", "baz" });
// simulate selection
items.setSelectedIndices(new int[] { 0, 2 });

Sometime later....

// get actual values
System.out.println(items.getSelectedValuesList());
// get indexes
System.out.println(Arrays.asList(items.getSelectedIndices()));
like image 101
Adam Avatar answered Mar 10 '26 04:03

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!