Anonymous Listeners - top of Musings page

by: Nicholas Duchon

Details about an anonymous inner class implementing a listener. For more information, perhaps more than anyone would want, you need to check out the Java Language Specification. 

In this example, I have created a button, then adding an anonymous inner class extending the class ActionListener, with comments added to the closing parentheses and brackets.

     JButton b = new JButton ("one");

     b.addActionListener (new ActionListener () {
         public void actionPerformed (ActionEvent e) {
           pressedButton (e.getActionCommand());
         } // end listener method
       } // end anonymous inner class definition
     ); // end accActionListener parameter

The method addActionListener is inherited from AbstractButton, and is part of the AWT event handling system. It's parameter is a class that implements the interface ActionListener, which has one required method: actionPerformend (ActionEvent).

Since ActionListener is an interface, when the keyword "new" is encountered, what follows is the parameter list for the constructor of a class, in this case ( ), an empty parameter list, and a definition of an anonymous inner class - a NEW class, without a name, that implements the ActionListener interface. 

After that, inside the { }'s, we are required to defined the method "actionPerformed (ActionEvent)" because this class is implementing the ActionListener interface, and we may put in any addition code that we find useful. Usually, we don't actually put any more code here since this construction is complicated enough as it is.

In this particular example, the response to a button press is to simply call a method (yellow highlighting) defined in the outer class called "pressedButton (String)", since "e.getActionComman()" will return a String associated with the action of pressing this button. The String will actually just be the label of the button, in this case.