O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Action Handling Using Anonymous Inner Classes

Problem

You want action handling with less creation of special classes.

Solution

Use anonymous inner classes.

Discussion

Anonymous inner classes are declared and instantiated at the same time, using the new operator with the name of an existing class or interface. If you name a class, it will be subclassed; if you name an interface, the anonymous class will extend java.lang.Object and implement the named interface. The paradigm is:

b.addActionListener(new ActionListener(  ) {
    public void actionPerformed(ActionEvent e) {
        showStatus("Thanks for pushing my second button!");
        }
});

Did you notice the }); by itself on the last line? Good, because it’s important. The } terminates the definition of the inner class, while the ) ends the argument list to the addActionListener method; the single argument inside the brackets is an argument of type ActionListener that refers to the one and only instance created of your anonymous class. Example 13-2 contains a complete example.

Example 13-2. ButtonDemo2c.java

import java.applet.*; import java.awt.*; import java.awt.event.*; /** Demonstrate use of Button */ public class ButtonDemo2c extends Applet { Button b; public void init( ) { add(b = new Button("A button")); b.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent e) { showStatus("Thanks for pushing my first button!"); } }); add(b = new Button("Another button")); b.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required