Java AWT Adapters are abstract classes from java.awt.event package introduced with JDK 1.1. Adapter classes make event handling simple and easy. Adapters usage replaces the listeners; adapters make event handling easy to the programmer. Every listener that includes more than one abstract method has got a corresponding adapter class. The advantage of adapter is that we can override any one or two methods we like instead of all. But incase of a listener, we must override all the abstract methods. For example, to close the window, all the 7 abstract methods of WindowListener should be overridden atleast with empty bodies. But is not the case with WindowAdapter. With WindowAdapter only one method windowClosing() is enough to override. Adapters can be used in inner classes also and is illustrated in "Java Frame Closing – Anonymous inner class".
Following table gives the list of important Java AWT listeners and their corresponding Java AWT Adapters classes.
ActionListener, ItemListener and TextListener do not have a corresponding adapter class as they contain only one abstract method.
Note: When an adapter is used, a separate class is to be created as the main class already extends Frame (Java does not support multiple inheritance).
Following table gives some important listeners and their corresponding adapter classes.
Listener Interface | Corresponding Adapter |
---|---|
WindowListener (7) | WindowAdapter |
MouseListener (5) | MouseAdapter |
MouseMotionListener (2) | MouseMotionAdapter |
KeyListener (3) | KeyAdapter |
FocusListener (2) | FocusAdapter |
The values in the parentheses indicate the abstract methods available in the listener interface.