Search code examples
javaswingjlistselectionchanged

JList: previous selected item


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?!


Solution

  • 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);
    }