Use Anonymous Inner Classes to Handle Events

Up to this point, the programs in this chapter have used a simple, straightforward approach to handling events in which the main class of the application has implemented the listener interface itself and all events are sent to an instance of that class. While this is perfectly acceptable, it is not the only way to handle events. Two other approaches are commonly used. First, you can implement separate listener classes. Thus, different classes could handle different events and these classes would be separate from the main class of the application. Second, you can implement listeners through the use of anonymous inner classes.

Anonymous inner classes are inner classes that don’t have a name. Instead, ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition 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.