CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2011
    Posts
    189

    Remove all listeners?

    Is there any way i could remove all the listeners from a JButton?
    I've encountered this problem as i defined most of my button listeners as following:

    s_UpdateButtonView.addActionListener(new ActionListener () {


    public void actionPerformed(ActionEvent e) {
    Now, in order to avoid some pretty nasty bugs i need to remove all the listeners for an object. I would have thought that adding a listener inside an If condition would only restrict it's usage to the times when the if condition is true, however it seems that this is not correct...
    I've tried looking it up on google, but i found some pretty ugly code, things that i cant understand at all and neither that i can paste.
    Now i know there is no removeAllListeners() method but i thought there is some way of detecting the names of Anonymous ( is that how are they called?) Listeners, so i can remove them with removeActionListener();?
    Thank you very much

  2. #2
    Join Date
    Nov 2011
    Posts
    189

    Re: Remove all listeners?

    I found a simple walkaround for the ones in need. Just make one huge listener with a conditional/switch statement (each branch of the if statement would contain a different action listener code), and activate each part of the listener by activating the representing if statement.
    THIS is not efficient in all the situations though, so if there is any better way, please post it

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Remove all listeners?

    Now i know there is no removeAllListeners() method but i thought there is some way of detecting the names of Anonymous ( is that how are they called?) Listeners, so i can remove them with removeActionListener();?
    What names?

    Save the listener to a variable and then use that to remove the listener ie

    Code:
    ActionListener myListener = new ActionListener () { ... }
    s_UpdateButtonView.addActionListener(myListener);
    
    ...
    
    s_UpdateButtonView.removeActionListener(myListener);
    If you have lots of them then consider using a Map to store the listeners and assigning your own names as the keys.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  4. #4
    Join Date
    Nov 2011
    Posts
    189

    Re: Remove all listeners?

    oh my... I feel so stupid now :-S... Before this I only knew how to do this by extending ActionListener, which ate a lot of time.. Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured