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

Get Just Java™ 2 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.