Domanda

I have a JList which runs code each time the value in the list is double-clicked. The value is populated when a button is pressed. My problem is each time I click the button and then double-click the JList value it will repeat the code by however many times the button is pressed.

For example, the first time everything looks great, but if I press the button again to change the JList value, it will execute the code for a double-click twice. If I press it a third time, it will execute the code three times and so on. I am new to this so apologies if this is an easy one. Thanks for any info. Code is below let me know if more is necessary.

public DefaultListModel results(StringBuilder message)
{   

    DefaultListModel model = new DefaultListModel();
    model.addElement(message);
    showOption.setModel(model);

    MouseListener mouseListener = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {

            if (e.getClickCount() == 2) 
            {
                int index = showOption.locationToIndex(e.getPoint());
                Object o = showOption.getModel().getElementAt(index);
                System.out.println("Double-clicked on: " + o.toString());
            }
        }
    };

    showOption.addMouseListener(mouseListener);
    return model;
}
È stato utile?

Soluzione

You are adding a new MouseListener each time results is called...

This...

DefaultListModel model = new DefaultListModel();
model.addElement(message);
showOption.setModel(model);

Shows that showOption is an existing instance of JList (which is good), but then you do...

MouseListener mouseListener = new MouseAdapter() {
    //...
};

showOption.addMouseListener(mouseListener);

Which adds ANOTHER MouseListener to the JList, so the each time this method is called, there will another MouseListener added to the JList.

Add a single MouseListener to the JList when you first create it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top