Mouse Listener in Java

Mouse Listener Tutorial in Java

In this blog we will study about Mouse Listener.To know more about java read and follow my blog.


Mouse Listener handles the events when the mouse is not in motion. Hence this listener will be notified or active when the state of mouse is changed. The MouseListener interface is found in java.awt.event package. AWT MouseAdapter class, which implements the MouseListener, MouseMotionListener, and MouseWheelListener interfaces.

Here we are discussing only Mouse Listener rest will be discussed in next blog.


How Java MouseListener works?


  • It starts when the mouse is clicked by a user.
  • Since the object is already registered with the listener, an event will be generated on clicking, pressing, entering, leaving or releasing the mouse.
  • This will help in the activation of the relevant method.
  • After the invocation, the Mouse event is passed to it.



The Mouse Listener API


The MouseListener Interface:- The signature of 5 methods found in MouseListener interface are given below:


Method Purpose
mouseClicked(MouseEvent) Called just after the user clicks the listened-to component.
mouseEntered(MouseEvent) Called just after the cursor enters the bounds of the listened-to component.
mouseExited(MouseEvent) Called just after the cursor exits the bounds of the listened-to component.
mousePressed(MouseEvent) Called just after the user presses a mouse button while the cursor is over the listened-to component.
mouseReleased(MouseEvent) Called just after the user releases a mouse button after a mouse press over the listened-to component.


// Write Program to illustrate the use of Mouse Listener in Java

import java.awt.*; 
import java.awt.event.*;
public class mouselis extends Frame implements MouseListener{
     TextField Text; 
    mouselis(){ 
        addMouseListener(this); 
         
        Text=new TextField(); 
        Text.setBounds(50,50,100,20); 
        add(Text); 
        setSize(300,300); 
        setLayout(null); 
        setVisible(true); 
    } 
    public void mouseClicked(MouseEvent e) { 
        Text.setText("Mouse Clicked"); 
    } 
    public void mouseEntered(MouseEvent e) { 
        Text.setText("Mouse Entered"); 
    } 
    public void mouseExited(MouseEvent e) { 
        Text.setText("Mouse Exited"); 
    } 
    public void mousePressed(MouseEvent e) { 
        Text.setText("Mouse Pressed"); 
    } 
    public void mouseReleased(MouseEvent e) { 
        Text.setText("Mouse Released"); 
    } 
  public static void main(String[] args) { 
    new mouselis(); 

}


Output:




for any query feel free to comment.





Comments