Coders Packet

Adapter classes in Java with example


In this guide, you will learn about various adapter classes in Java, their implementation and usefulness in developing GUI projects with an easy and understandable example.

Java adapter classes with example

Before we start with the implementation of adapter classes, Let's understand what adapter classes in Java really are. The adapter class in Java offers default enforcement of all methods of an interface. But, there is no real need for us to modify all methods of an interface. Then, why do we need to use adapter classes in Java? simply put, adapter classes reduce the coding burden by making the code highly reusable. It enables a way to include relevant patterns in class. Additionally, it can assist different unrelated classes to work simultaneously or together. As we know, the adapter class modifies all the methods of an interface by default so, we are only required to modify some methods.

Now that we understand adapter classes in Java, let's take an example and start coding to understand its implementation. 

First, Let's import the packages in which we can find the adapter class in Java. Where can you find adapter classes in Java? You can find the adapter classes in the java.awt.event, java.awt.dnd and javax.swing.event packages. 

import java.awt.*;
import java.awt.event.*;



then, we define a class named 'example' which inherits the properties or attributes of the adapter class – MouseMotionAdapter. The class MouseMotionAdapter is an abstract adapter class that can be used for receiving mouse motion events. You should also note that all methods of this class are empty by default. 

Here, the MouseMotionListener is a java interface that is altered whenever the mouse is moved or dragged about. We are also using setSize(), setLayout(), setVisible() methods. setSize() is a method in the Java vector class that is used to set the size of a vector. The layout is set as null in this program, it means that fixed locations and sizes don’t change with the environment. Do note that, setLayout(null) is very useful for making quick prototypes.

The mouseDragged method is summoned when a cursor is being dragged in a window listening for mouse motion event of type MouseEvent.

In this code, we have set the color of the graphics as blue. And lastly, the getGraphics() method gives us a graphic context for sketching or drawing in the component you designed.

Since we learned about the methods required to implement adapter classes and the functions they perform, let’s take a look at the final code!

import java.awt.*;
import java.awt.event.*;
public class example extends MouseMotionAdapter{
    Frame f;
        f=new Frame("Mouse Motion Adapter");

    public void mouseDragged(MouseEvent e) {
        Graphics g=f.getGraphics();
    public static void main(String[] args) {
        new example();

let's check out the application of the code we developed! 

Download Complete Code


No comments yet