我想爲JList
寫一個ListSelectionListener
,它知道用戶正在選擇哪個列表項,以及用戶正在選擇哪個列表項。所以,如果列表中有{Apple, Orange, Pear}
三個項目,目前的選擇是在Orange
和用戶選擇Pear
,則:如何獲取Swing ListSelectionEvent的「源」項?
srcFruit
是Orange
;和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
,沒有默認的選擇。當我採取以下措施:
- 點擊
Orange
- 點擊
Pear
- 點擊
Orange
再次
這裏的打印出我得到:
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
。 爲什麼不呢?!?!
在此先感謝!