从 JList 中获取多个选定项
Get multiple selected items from a JList
我正在创建一个屏幕,上面有四个列表。基本上是两对列表,您可以在其中一个列表上 select 行并将它们移动到对中的另一个列表。
查看文档,我需要每个列表的 ListSelectionModel 以确定哪些行已被 selected。我将使用 [Sel] 或 [Des] 按钮进行实际传输。
文档和示例说我需要一个 ListSelectionListener,但由于在用户单击按钮之前我不会访问该模型,我真的需要一个侦听器吗?如果我没有侦听器,模型是否仍会设置 getMinSelectionIndex、getMaxSelectionIndex 和 isSelectedIndex?
but as I will not access the model until the user clicks on the button do I actually need a listener?
没有。只需要侦听器来通知列表的项目被选中或取消选中,并且由于您正在等待来自 JButton 的通知,它的 ActionListener 就是您所需要的。
Will the model still have the getMinSelectionIndex, getMaxSelectionIndex and isSelectedIndex set if I do not have a listener?
这与听者无关。如果您要求,该模型仍应为您提供此信息。
但为什么要问这些问题呢?这很容易通过简单的测试发现。
您不需要侦听器,侦听器仅用于在您不需要的其他地方保持同步。
选择事件发生后,您可以随时访问所选索引。方法 JList.getSelectedIndices returns 当前选定索引的数组,getSelectedValuesList() returns 实际项目取决于你想要什么....
JList<String> items = new JList<String>(new String[] { "foo", "bar", "baz" });
// simulate selection
items.setSelectedIndices(new int[] { 0, 2 });
稍后....
// get actual values
System.out.println(items.getSelectedValuesList());
// get indexes
System.out.println(Arrays.asList(items.getSelectedIndices()));
我正在创建一个屏幕,上面有四个列表。基本上是两对列表,您可以在其中一个列表上 select 行并将它们移动到对中的另一个列表。
查看文档,我需要每个列表的 ListSelectionModel 以确定哪些行已被 selected。我将使用 [Sel] 或 [Des] 按钮进行实际传输。
文档和示例说我需要一个 ListSelectionListener,但由于在用户单击按钮之前我不会访问该模型,我真的需要一个侦听器吗?如果我没有侦听器,模型是否仍会设置 getMinSelectionIndex、getMaxSelectionIndex 和 isSelectedIndex?
but as I will not access the model until the user clicks on the button do I actually need a listener?
没有。只需要侦听器来通知列表的项目被选中或取消选中,并且由于您正在等待来自 JButton 的通知,它的 ActionListener 就是您所需要的。
Will the model still have the getMinSelectionIndex, getMaxSelectionIndex and isSelectedIndex set if I do not have a listener?
这与听者无关。如果您要求,该模型仍应为您提供此信息。
但为什么要问这些问题呢?这很容易通过简单的测试发现。
您不需要侦听器,侦听器仅用于在您不需要的其他地方保持同步。
选择事件发生后,您可以随时访问所选索引。方法 JList.getSelectedIndices returns 当前选定索引的数组,getSelectedValuesList() returns 实际项目取决于你想要什么....
JList<String> items = new JList<String>(new String[] { "foo", "bar", "baz" });
// simulate selection
items.setSelectedIndices(new int[] { 0, 2 });
稍后....
// get actual values
System.out.println(items.getSelectedValuesList());
// get indexes
System.out.println(Arrays.asList(items.getSelectedIndices()));