-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHoverSquares.java
More file actions
77 lines (57 loc) · 1.57 KB
/
Copy pathHoverSquares.java
File metadata and controls
77 lines (57 loc) · 1.57 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
Exam 2 event handler question.
@author Jim Teresco
@version Spring 2020
*/
public class HoverSquares extends MouseAdapter implements Runnable {
// square size
public static final int SIZE = 50;
// list of squares currently on the screen
private java.util.List<Point> upperLefts;
private JPanel panel;
/**
The run method to set up the graphical user interface
*/
@Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HoverSquares");
frame.setPreferredSize(new Dimension(800,800));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// JPanel with a paintComponent method
panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the squares
for (Point p : upperLefts) {
g.fillRect(p.x, p.y, SIZE, SIZE);
}
}
};
frame.add(panel);
panel.addMouseListener(this);
panel.addMouseMotionListener(this);
upperLefts = new ArrayList<Point>();
frame.pack();
frame.setVisible(true);
}
/**
Mouse press event handler to create a new Square with upper left at
the press point.
@param e mouse event info
*/
@Override
public void mousePressed(MouseEvent e) {
upperLefts.add(e.getPoint());
panel.repaint();
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new HoverSquares());
}
}