我正在尝试为 JList
编写一个 ListSelectionListener
,它知道用户正在从哪个列表项中选择,以及用户正在选择哪个列表项。因此,如果列表中包含三个项目 {Apple, Orange, Pear}
,并且当前选择的是 Orange
并且用户选择了 Pear
,然后:
srcFruit
是橙色
;和destFruit
是Pear
这是我的代码:
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent fruitSelectionEvent) {
printSourceAndDestFruit(myList, fruitSelectionEvent);
}
});
private void printSourceAndDestFruit(JList list, ListSelectionEvent event) {
FruitVO srcFruit = (FruitVO)list.getModel().getElementAt(event.getFirstIndex());
FruitVO destFruit = (FruitVO)list.getModel().getElementAt(event.getLastIndex());
System.out.println("srcFruit = " + srcFruit.getName() + " and destFruit = " = destFruit.getName());
}
当应用程序加载并初始化JList
时,没有默认选择。当我采取以下行动时:
- 点击
橙色
- 点击
梨
- 再次点击
橙色
这是我得到的打印输出:
srcFruit = Orange and destFruit = Pear
srcFruit = Orange and destFruit = Pear
我哪里错了? getFirstIndex()
/getLastIndex()
是否存在错误或只是未使用正确的 Swing 方法?
这是我应该看到的输出:
srcFruit = Orange and destFruit = Pear
srcFruit = Pear and destFruit = Orange
所以即使我进行了 3 次选择(鼠标点击),因为我第一次点击 Orange
并不是从一个值到下一个值的变化,我相信不触发并调用 printSourceAndDestFruit
是正确的。我选择 Pear
并且正确地声明 srcFruit
是 Orange
并且 destFruit
是 Pear
。但是,当我单击返回 Orange
时,第二个 println 应该将 srcFruit
作为 Pear
并将 destFruit
作为 Orange
。 为什么不呢?!?!
提前致谢!
最佳答案
第一个和最后一个索引不是你想的那样。这是 javadoc 所说的内容:
getFirstIndex()
Returns the index of the first row whose selection may have changed.
getLastIndex()
Returns the index of the last row whose selection may have changed.
因此,由于每次单击时梨和橙子的选择都会发生变化,并且由于梨在列表中位于橙子之后,因此 getFirstIndex()
始终返回 Orange 和 getLastIndex()
总是返回 Pear。
如果要将新选择与上一个进行比较,则将上一个选择保存在某个成员变量中,并在每次选择更改时将其与新选择进行比较,并且 getValueIsAdjusting()
返回 false。
关于java - 如何获取 Swing ListSelectionEvent 的 "source"项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887161/