Mastering Java Swing
Draw On Mouse Click
Keyboard and Mouse InteractionYou can use the Mouse Listener to register mouse clicks. In this code we draw a blue square where we click in the screen.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Click to Draw a Square");
DrawingPanel panel = new DrawingPanel();
// Set up the GUI
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
}
class DrawingPanel extends JPanel {
private int squareX = -50; // Initial position offscreen
private int squareY = -50;
private final int SQUARE_SIZE = 50; // Fixed size for the square
public DrawingPanel() {
// Add MouseListener to capture click events
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
squareX = e.getX() - SQUARE_SIZE / 2; // Center the square on click
squareY = e.getY() - SQUARE_SIZE / 2;
repaint(); // Redraw the panel
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // Clear the panel for fresh drawing
g.setColor(Color.BLUE); // Set the square's color
g.fillRect(squareX, squareY, SQUARE_SIZE, SQUARE_SIZE); // Draw the square
}
}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.