简体   繁体   中英

Get multiple selected items from a 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.

样本屏幕

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?

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()));

but as I will not access the model until the user clicks on the button do I actually need a listener?

No. The listener is just needed for notification of the list's items being selected or deselcted, and since you're waiting for notification from the JButton, its ActionListener is all that you need.

Will the model still have the getMinSelectionIndex, getMaxSelectionIndex and isSelectedIndex set if I do not have a listener?

This has nothing to do with the listener. The model should still give you this information if you request it.

But why ask these questions? This is easily discoverable by simple testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM