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 ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.