Search code examples
javaswingawtactionlistener

ActionListener called twice, added once


I created one JFrame. This JFrame contains a JLabel, which contains some JButtons. The JButtons have an ActionListener (called MainFrameListener). When the arrowButton Button is clicked a method is executed by the code. This method removes all ActionListeners from the old Buttons with foodButton.removeActionListener(new MainFrameListener());

But although I removed the Listener the Button has still two buttons. Of course I already searched on the Internet to fix the problem and I found a line of code which shows the amount of Listeners for one Button.

System.out.println("Count of listeners: " + ((JButton) e.getSource()).getActionListeners().length);

The first time I click on the buttons Java says there are two buttons. When I click on the arrowButton the other menu opens and the buttons are removed. That's all like I want. When I click the arrowBackButton the application sends me back to the MainFrame. That's perfect. But when I click on the arrowButton again the Console says that I have two listeners registered for the Buttons. And the sound which comes on the click is played two times.

I don't understand that because I removed the Listeners. Is there any better method to remove Listeners?


Solution

  • foodButton.removeActionListener(new MainFrameListener()); wont remove anything since you are removing a newly created object that has never been added to foodButton. Keep a reference to your listener and remove it later like this:

    MainFrameListener listener = new MainFrameListener();
    foodButton.addActionListener(listener);
    //and later somewhere else
    foodButton.removeActionListener(listener);
    

    But my advice is to avoid adding/removing listeners in the first place.