问题
I have a JList and register a selection handler (ListSelectionListener). Now I need to now the previous selected item/index.
Up to now, I save the last selected item on my own. Is there a better way to do so? In other words: Is there are methode/best practice which I miss all the years?!
回答1:
One of my list is single-selection-only. like kleopatra says. The event data does not help here.
That is not what Kleopatra said. The event data does help. You just can't assume that the first index represents the selected row and the last index represents the previous row.
As Kleopatra suggested you need to do further checking. Something like:
public void valueChanged(ListSelectionEvent e)
{
JList list = (JList)e.getSource();
int selected = list.getSelectedIndex();
int previous = selected == e.getFirstIndex() ? e.getLastIndex() : e.getFirstIndex();
System.out.println();
System.out.println("Selected:" + selected);
System.out.println("Previous:" + previous);
}
回答2:
You don't need to write your custom code to store the previous selected item in list. JList provide a ListSelectionListener which will do the work for you. Here is the way to get last selected item.
customList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
//Previous Selected Item index will be obtained by arg0.getFirstIndex()
// Similarly Currently Selected Item index will be obtained by this method arg0.getLastIndex()
}
});
来源:https://stackoverflow.com/questions/9191012/jlist-previous-selected-item