JList: previous selected item

丶灬走出姿态 提交于 2019-12-12 13:13:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!