Get multiple selected items from a JList

耗尽温柔 提交于 2019-12-10 21:56:43

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/28431432/get-multiple-selected-items-from-a-jlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!