Adapter Classes in Java
In Java's event handling mechanism, adapter classes are abstract classes provided by the Java
AWT (Abstract Window Toolkit) package for receiving various events. These classes contain
empty implementations of the methods in an event listener interface, providing a convenience
for creating listener objects.
The adapter classes in Java are
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
These adapter classes implement interfaces like WindowListener, KeyListener,
MouseListener, FocusListener, ContainerListener, and ComponentListener respectively,
which contain methods related to specific events.
Need for Adapter Classes
To comprehend the role of adapter classes, one must first understand the concept of event
listeners in Java. An event listener is an interface that contains methods invoked when certain
events occur.
For instance, the WindowListener interface has seven different methods corresponding to
various window events, like window opening, closing, deiconifying, etc. If a class
implements this interface, it's required to provide implementations for all seven methods,
even if it's only interested in one event.
This is where adapter classes come in handy. Since they provide default (empty)
implementations for all event handling methods, you can create a subclass from an adapter
class, and override only those methods you're interested in.
Example:
Simple example of how to use a Java Adapter Class. Use the WindowAdapter class to close a
window −
import [Link].*;
import [Link].*;
class WindowExample extends Frame {
WindowExample() {
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WindowExample();
}
}