Mastering Java Swing
Interacting With The Mouse
Keyboard and Mouse InteractionThe MouseMotionListener interface allows a program to respond to mouse movements and dragging events. In this example, we’ll display the mouse’s x and y coordinates on the screen as you move or drag the mouse.
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Position Example");
JLabel positionLabel = new JLabel("Move the mouse to see position");
// Set up the GUI
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // Absolute positioning
positionLabel.setBounds(20, 20, 300, 20);
frame.add(positionLabel);
// Add a MouseMotionListener to track mouse movements
frame.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
positionLabel.setText("Mouse Moved Position: X = " + e.getX() + ", Y = " + e.getY());
}
@Override
public void mouseDragged(MouseEvent e) {
positionLabel.setText("Mouse Dragged Position: X = " + e.getX() + ", Y = " + e.getY());
}
});
frame.setVisible(true);
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.