Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata