Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
- It assists the unrelated classes to work combinedly.
- It provides ways to use classes in different ways.
- It increases the transparency of classes.
- It provides a way to include related patterns in the class.
- It provides a pluggable kit for developing an application.
- It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter classes with their corresponding listener interfaces are given below.
java.awt.event Adapter classes
Adapter class | Listener interface |
---|---|
WindowAdapter | WindowListener |
KeyAdapter | KeyListener |
MouseAdapter | MouseListener |
MouseMotionAdapter | MouseMotionListener |
FocusAdapter | FocusListener |
ComponentAdapter | ComponentListener |
ContainerAdapter | ContainerListener |
HierarchyBoundsAdapter | HierarchyBoundsListener |
java.awt.dnd Adapter classes
Adapter class | Listener interface |
---|---|
DragSourceAdapter | DragSourceListener |
DragTargetAdapter | DragTargetListener |
javax.swing.event Adapter classes
Adapter class | Listener interface |
---|---|
MouseInputAdapter | MouseInputListener |
InternalFrameAdapter | InternalFrameListener |
Java WindowAdapter Example
In the following example, we are implementing the WindowAdapter class of AWT and one its methods windowClosing() to close the frame window.
AdapterExample.java
Output:
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The MouseListener interface is added into the frame to listen the mouse event in the frame.
MouseAdapterExample.java
Output:
Java MouseMotionAdapter Example
In the following example, we are implementing the MouseMotionAdapter class and its different methods to listen to the mouse motion events in the Frame window.
MouseMotionAdapterExample.java
Output:
Java KeyAdapter Example
In the following example, we are implementing the KeyAdapter class and its method.
KeyAdapterExample.java
Output: