-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMouseDrawingApp.java
More file actions
38 lines (32 loc) · 1.05 KB
/
MouseDrawingApp.java
File metadata and controls
38 lines (32 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//Combining Event Handling + Painting to make interactive drawings using mouse
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseDrawingApp extends JPanel {
private int x = -1, y = -1;
public DrawingApp() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint(); // triggers paintComponent
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (x >= 0 && y >= 0) {
g.setColor(Color.MAGENTA);
g.fillOval(x - 10, y - 10, 20, 20); // draw circle at click point
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Drawing");
MouseDrawingApp panel = new MouseDrawingApp();
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}