Java Notes

Anonymous Listeners

Using anonymous inner class listeners - a common idiom

There is no need to define a named class simply to add a listener object to a button. Java has a somewhat obscure syntax for creating an anonymous innner class listener that implements an interface. There is no need to memorize the syntax; just copy and paste it each time. For example,

class myPanel extends JPanel {
. . .
    public MyPanel() {
        . . .  //in the constructor
        JButton b1 = new JButton("Hello");
        b1.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // do something for button b1
                }
            }
        );

Creates a class

The above example creates a subclass of Object that implements the ActionListener interface. The compiler creates names for anonymous classes. The JDK typically uses the enclosing class name followed by $ followed by a number, eg, you may see a MyPanel$1.class file generated by the compiler.