method getSelectionIndex() in ListSelectionListener

寵の児 提交于 2019-12-11 18:23:21

问题


For example, I have a JList named across_list that containing a list of items and now I add a ListSelectionListener to that JList

Considering these lines of code:

class AcrossListHandler implements ListSelectionListener {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        JList lsm = (JList) e.getSource();
        int selected_index = lsm.getMaxSelectionIndex();            
            if (selected_index >= 0){
                System.out.println(selected_index);
            }
        }  
     }       
}

I have a question that: Why the line "System.out.println()" print 2 values of selected_value while i just click 1 time on an index in JList ???


回答1:


The listSelectionListener registered by the ui-delegate marks the selection change as being in-process on mousePressed and resets that flag in mouseReleased, making it final. If you want to only react only to changes that are finalized, you can query the valueIsAdjusting property and do nothing if true:

class AcrossListHandler implements ListSelectionListener {

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) return;
        // do stuff
    }
}


来源:https://stackoverflow.com/questions/16036391/method-getselectionindex-in-listselectionlistener

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