O'Reilly logo

Just Java™ 2 by Peter van der Linden

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

Tips for Slimming Down Handler Code

Inner classes are intended for event handlers. The inner classes allow you to put the event-handling class and method right next to where you declare the control or register the callback listener. Anonymous classes are a refinement of inner classes, allowing you to combine the definition of the class with the instance allocation. The following example shows the code rewritten using an anonymous class:

import javax.swing.*;import java.awt.event.*;public class CloseDemo2 {    public static void main(String[] args) {          JFrame jframe = new JFrame("Example");          jframe.setSize(400,100);          jframe.setVisible(true);          jframe.addWindowListener( new WindowListener() { // anon. class

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