Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 331
Marcel Jaeschke Avatar asked May 23 '26 23:05

Marcel Jaeschke


1 Answers

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);
}
like image 168
camickr Avatar answered May 26 '26 12:05

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!