Trung Bún
Trung Bún

Reputation: 1147

method getSelectionIndex() in ListSelectionListener

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

Upvotes: 0

Views: 180

Answers (1)

kleopatra
kleopatra

Reputation: 51535

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
    }
}

Upvotes: 2

Related Questions