Search code examples
javaswingjlistlistselectionlistener

ListSelectionEvent, firing an event when clicking the currently selected item in JList


Let 'x' be an item in the JList. When I click it for the first time, the event fires, when I click it again, the event does not fire. I have to click some other item and then come back to 'x'.

How can I fire the event repeatedly from 'x' without having to deal with other items.

This is my code:

public void valueChanged(ListSelectionEvent e) {

    if (e.getValueIsAdjusting() == false) {

       if (list.getSelectedIndex() == -1) {} else {
            String clicked = (String)list.getSelectedValue();



            //method to fire is here

        }
    }
    updateDisplays();

}

Solution

  • The ListSelectionListener reflects changes to the lists selection, you could use a MouseListener instead...

    For example...

    MouseListener ml = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            if (SwingUtilities.isLeftMouseButton(evt) && evt.getClickCount() == 1) {
                if (list.getSelectedIndex() != -1) {
                    int index = list.locationToIndex(evt.getPoint());
                    System.out.println("You clicked item  @ " + index);
                }
            }
        }
    }
    
    list.addMouseListener(ml);