×

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of the various methods used by Graphical User Interface (GUI) programming languages like Java to handle events.

The user interacts with the system via connected images and graphics in event-driven GUI programming. This means that any user-initiated action, such as moving the mouse to alter the coordinates of the mouse pointer on the screen, clicking a button, or scrolling a webpage, is regarded as a separate event.

Listener interfaces are implemented by default using Java adapter classes. You won't be required to implement every method of listener interfaces if you inherit from the adapter class. Code is thus saved.

The java.awt.event, java.awt.dnd, and javax.swing.event packages contain the adapter classes.

Benefits of utilising adapter classes 

  1. Include helping unrelated classes function together.
  2. It offers diverse approaches to using classes.
  3. It makes lessons more transparent.
  4. It offers a means of incorporating similar patterns into the class.
  5. It offers a pluggable development kit for applications.
  6. It makes the class more versatile.
Adapter ClassListener Interface
Mouse AdapterMouse Listener
Window AdapterWindow Listener
KeyAdapterKeyListener  
Mouse Motion AdapterMouseMotion Listener
Container AdapterContainer Listener
Componenet AdapterComponent Listener

MouseAdapter1.java

import java . awt . * ;  
import java . awt . event . * ;  
public class MouseAdapter1 extends MouseAdapter{  
    Frame f1 ;   // Creating a frame
    // Default constructor
    MouseAdapter1 ( ) {  
        f1=new Frame( " M ouse Adapter " ) ;  // Setting the name of the frame as MouseAdapter
        f1 . addMouseListener ( this ) ; 
        f1 . setSize ( 400 , 400 ) ;  // Setting the size of frame 
        f1 . setLayout ( null ) ;  
        f1 . setVisible ( true ) ;  // Giving visibility to the frame
     // This inner class is used to close the window
        f1 . addWindowListener (new WindowAdapter ( ) 
{    
            public void windowClosing (WindowEvent e1) {    
                f1 . dispose ( ) ;    
            }    
        });   
    }  
    public void mouseClicked(MouseEvent e) {  
        Graphics g1=f1 . getGraphics ( ) ;  
        g1 . setColor ( Color . BLACK ) ;  
        g1 . fillOval (e.getX(), e.getY(), 20, 15);    
    }   
public static void main(String[] args) {  
    new MouseAdapter1();  
}  
}

Output

Use Of Adapter class in Java

Java Window Adapter Program

This program is used to create windows using awt packages

Adapter.java

// Necessary  packages are imported
import java.awt.*;    
import java.awt.event.*;    
public class Adapter {  
// Creating a Frame  f1  
    Frame f1;    
// default class constructor  
    Adapter() {    
// creating a frame with the title  
        f1 = new Frame ("Adapter Windows");    
// overriding the window closing() method   
        f1.addWindowListener (new WindowAdapter() {    
            public void windowClosing (WindowEvent e1) {    
                f1.dispose();    
            }    
        });    
         // setting the size of the frame
        f1.setSize (350, 450);    
        // setting the size of the frame
        f1 . setLayout ( null ) ;    
        f1 . setVisible ( true ) ;    
    }    
// main method  
public static void main ( String [ ] args ) {    
    new Adapter ( ) ;    
// Default constructor 
// Name of the constructor should be same as class name
}    // main method for the program
}  // Adapter

Output

Use Of Adapter class in Java

Java KeyAdapter Program

KeyAdapter1.java

//Importing the required packages
import java.awt.*;    
import java.awt.event.*;    
public class KeyAdapter1 extends KeyAdapter {    
// Creating label and textarea  component variables
    Label l1;    
    TextArea area1;    
    Frame f1;    
// class constructor  
    KeyAdapter1() {    
// creating the Frame with the title  
        f1 = new Frame ("Adapter for Key ");    
// creating the Label  
        l1 = new Label();    
// setting the location of the label   
        l1.setBounds (20, 50, 200, 20);    
// creating the text area  
        area1 = new TextArea();  
        area1.setBounds (20, 80, 300, 300);    
        area1.addKeyListener(this);    
// Adding the label and text area to the frame by using the add  method
        f1.add(l1);  
       f1.add(area1);    
// setting the size  
        f1.setSize (400, 400);  
//layout of the frame  
        f1.setLayout (null);
//visibility of the frame    
        f1.setVisible (true);
        f1.addWindowListener (new WindowAdapter() {    
            public void windowClosing (WindowEvent e) {    
                f1.dispose();    
            }    
        });    
    }    
    public void keyReleased (KeyEvent e) {    
        String text1 = area1.getText();    
// splitting the given String
        String words1[] = text1.split ("\\s");    
        l1.setText ("Words: " + words1.length + " Characters:" + text1.length());    
    }    
  // main method for the program 
    public static void main(String[] args) {    
        new KeyAdapter1();    
    }    
}   

Output

Use Of Adapter class in Java

Related Topics

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.