×

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

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

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.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.