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 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.