How to implement Java mouse listener events and their functions?
In Java, you can implement mouse listening events by using the MouseListener interface and MouseAdapter class. Below is a simple example code demonstrating how to implement mouse listening events and handle mouse click events.
import javax.swing.*;
import java.awt.event.*;
public class MouseListenerExample extends JFrame {
public MouseListenerExample() {
super("Mouse Listener Example");
JLabel label = new JLabel("Click Here");
add(label);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: (" + e.getX() + ", " + e.getY() + ")");
}
});
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
In the code above, we created a JFrame window and added a JLabel to it. We then added a MouseListener event listener using the label.addMouseListener() method, implementing the mouseClicked() method from the MouseListener interface using an anonymous inner class of the MouseAdapter class. In the mouseClicked() method, we printed out the coordinates of where the mouse click event occurred.
When the user clicks on a JLabel label, the program will output the coordinates of where the mouse click event occurred. This is how to implement mouse listening events and their functionality in Java.