Question

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();

}
Was it helpful?

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);

OTHER TIPS

You can add a MouseListener and watch for clicks. Note that a click that changes the selection will fire both the MouseListener and your ListSelectionListener.

Another option is to immediately clear the selection from your ListSelectionListener; that way the next click will reselect and retrigger, although you will lose the ability to navigate through items with the keyboard.

It seems like sort of an unusual UX decision, though, to assign significance to a click on an already selected item in a list.

Adding based on your question comments: If you go the MouseListener route, I recommend looking for double-clicks instead of single-clicks if the click is going to execute an action (especially if the action changes data and is not undoable). Also note that your ListSelectionListener will execute actions as you navigate through the list with the keyboard, which may not be what you intend.

If your commands in your history list are typed, you could also consider using a drop-down combo box for both command entry and the history list, where a selection from history fills in the command text but does not execute. You'd also have an opportunity to add auto-complete from command history.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top