In Java Swing, we can capture mouse events such as clicking, dragging, and releasing the mouse using the MouseListener
and MouseMotionListener
interfaces.
Following is an example code that demonstrates how to capture mouse events in Java Swing:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class MouseEventDemo extends JFrame implements MouseListener, MouseMotionListener {
private JLabel label;
public MouseEventDemo() {
super("MouseEvent Demo");
label = new JLabel("No mouse event captured yet.", SwingConstants.CENTER);
label.setPreferredSize(new Dimension(300, 100));
add(label, BorderLayout.CENTER);
addMouseListener(this);
addMouseMotionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse pressed at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse released at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse entered at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse exited at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseDragged(MouseEvent e) {
label.setText("Mouse dragged at (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseMoved(MouseEvent e) {
label.setText("Mouse moved at (" + e.getX() + ", " + e.getY() + ")");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseEventDemo());
}
}
In the example above, we create a JFrame
and add a JLabel
to display the mouse events captured. We implement the MouseListener
and MouseMotionListener
interfaces and override their methods to capture the different mouse events. We then register the frame as a listener for mouse events using the addMouseListener
and addMouseMotionListener
methods. Finally, we set the frame visible and pack it to the preferred size.
When the user clicks, presses, releases, enters, or exits the mouse, or drags or moves the mouse, the corresponding method will be called and the label’s text will be updated with the coordinates of the mouse event.
Sample output: