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 e) {
                showStatus("Thanks for pushing my second button!");
            }
        });
    }
}

The real benefit of these anonymous inner classes, by the way, is that they keep the action handling code in the same place that the GUI control is being instantiated. This saves a lot of looking back and forth to see what a GUI control really does.

Those ActionListener objects have no instance name and appear to have no class name: is that possible? The former yes, but not the latter. In fact, class names are assigned to anonymous inner classes by the compiler. After compiling and testing ButtonDemo2c with JDK 1.2, I list the directory in which I ran the program:

C:javasrcgui>ls -1 ButtonDemo2c*
ButtonDemo2c$1.class
ButtonDemo2c$2.class
ButtonDemo2c.class
ButtonDemo2c.htm
ButtonDemo2c.java
C:javasrcgui>

Those first two are the anonymous inner classes. Note that a different compiler might assign different names to them; it doesn’t matter to us. A word for the wise: don’t depend on those names!

See Also

Most IDEs (see Section 1.2) have drag-and-drop GUI builder tools that will make this task easier, at least for simpler projects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.120.57