Java MouseMotionListener in AWT
Last Updated :
07 Nov, 2023
Java AWT (Abstract Window Toolkit) provides varied event listeners to wield exploiter interactions. One of these is the Java MouseMotionListener, which is secondhand to track sneak out motion events. This hearer allows you to respond to the mouse’s front, such as sleuthing when the mouse is dragged or moved within a component. In this clause, we wish research the MouseMotionListener in Java AWT, including its syntax, methods, constructors, and a sample code with comments.
Class Declaration
The MouseMotionListener user interface is disunited of the java.awt.event box. To use it, you must follow through this user interface in your classify. Here’s the syntax of class declaration for a assort that uses the MouseMotionListener:
Java
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
class YourClass implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
|
MouseMotionListener Class Methods
This method is called when the mouse is dragged with a button down. It provides information about the mouse event, such as the mouse’s location and the component it occurred on.
|
This method is called when the mouse is moved without any buttons being pressed. It also provides information about the mouse event.
|
Example of MouseMotionListener
Below is the implementation of MouseMotionListener:
Java
import java.awt.*;
import java.awt.event.*;
class MouseMotionExample extends Frame implements MouseMotionListener {
Label label;
MouseMotionExample() {
label = new Label( "Mouse Coordinates: " );
add(label);
addMouseMotionListener( this );
setSize( 400 , 400 );
setLayout( null );
label.setBounds( 100 , 180 , 200 , 20 );
label.setAlignment(Label.CENTER);
setVisible( true );
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
label.setText( "Mouse Coordinates: (" + x + ", " + y + ")" );
}
public static void main(String[] args) {
new MouseMotionExample();
}
}
|
Output:
Final Output of the Program:
Conclusion
In this article explored the usage of the MouseMotionListener in Java AWT to track mouse motion events within a graphical user interface. We covered the syntax of class declaration, the two essential methods for handling mouse motion events, and how to position a label to display the mouse coordinates in the center of the window.
Share your thoughts in the comments
Please Login to comment...