MouseMotion Listener in Java
Mouse-motion events notify when the user
uses the mouse (or a similar input device) to move the onscreen cursor. If an application requires the detection of both mouse events
and mouse-motion events, use the MouseInputAdapter class, which implements the MouseInputListener a convenient interface that implements
both the MouseListener and MouseMotionListener interfaces.
Alternatively, use the corresponding MouseAdapter AWT class, which implements the
MouseMotionListener interface, to create a MouseMotionEvent and override the
methods for the specific events.
Class Declaration
Following is the declaration for java.awt.event.MouseMotionListener
interface:
public interface MouseMotionListener
extends EventListener
Methods inherited
This class inherits methods from the
following interfaces:
- java.awt.event.EventListener
 
Mouse-Motion Listener API
:
The corresponding adapter classes are MouseMotionAdapter and MouseAdapter.
Method 
 | 
  
Purpose 
 | 
 
mouseDragged(MouseEvent) 
 | 
  
Called in response to the user moving the mouse while
  holding a mouse button down. This event is fired by the component that fired
  the most recent mouse-pressed event, even if the cursor is no longer over
  that component. 
 | 
 
mouseMoved(MouseEvent) 
 | 
  
Called in response to
  the user moving the mouse with no mouse buttons pressed. This event is fired
  by the component that's currently under the cursor. 
 | 
 
Each mouse-motion event method has a
single parameter — and it's not called MouseMotionEvent! Instead, each
mouse-motion event method uses a MouseEvent argument. See The
MouseEvent API for information about using MouseEvent objects.
How to add Mouse-Motion Listener:
To add mouse motion
listener we used method called addMouseMotionListener().
Example:
Button.addMouseMotionListener (this);
 // here I add this Listener on
button so I write button here.
Method 
 | 
  
Description 
 | 
 
public
  void addMouseMotionListener(MouseMotionListener object) 
 | 
  
where object is an object
  of the class that has implemented MouseMotionListener interface. Doing
  this, registers the class to listen and respond to mouse move and drag MouseEvent. 
 | 
 
// Program to illustrate
the use of MouseMotionListener in Java.
import java.awt.*;
import java.awt.event.*;
public class Mousemotion1 implements
MouseMotionListener {
    
TextField td;
   
Mousemotion1()
   
{
    
Frame f=new Frame();
    
td=new TextField("Example of Mouse Motion Listener");
    
f.add(td);
    
td.addMouseMotionListener(this);
    
f.setSize(500,500);
    
f.setVisible(true);
    
f.setLayout(null);
   
}
   
public void mouseDragged(MouseEvent e)
   
{
    
td.setText("Mouse Dragged");
   
}
   
public void mouseMoved(MouseEvent e) {} 
public static void main(String[] args)
{  
   
new Mousemotion1();  
} 
}
Output:
for any query feel free to comment.




Comments
Post a Comment