1 |
import java.awt.event.MouseEvent; |
2 |
import java.awt.event.MouseListener; |
3 |
import java.awt.Dimension; |
4 |
import java.awt.Graphics; |
5 |
import java.awt.Graphics2D; |
6 |
import java.awt.Rectangle; |
7 |
import javax.swing.JPanel; |
8 |
|
9 |
/** |
10 |
A rectangle panel displays a rectangle that a user can |
11 |
move by clicking the mouse. |
12 |
*/ |
13 |
public class RectanglePanel extends JPanel |
14 |
{ |
15 |
/** |
16 |
Constructs a rectangle panel with the rectangle at a |
17 |
default location. |
18 |
*/ |
19 |
public RectanglePanel() |
20 |
{ |
21 |
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); |
22 |
|
23 |
// the rectangle that the paint method draws |
24 |
box = new Rectangle(BOX_X, BOX_Y, |
25 |
BOX_WIDTH, BOX_HEIGHT); |
26 |
|
27 |
// add mouse press listener |
28 |
|
29 |
class MousePressListener implements MouseListener |
30 |
{ |
31 |
public void mousePressed(MouseEvent event) |
32 |
{ |
33 |
int x = event.getX(); |
34 |
int y = event.getY(); |
35 |
box.setLocation(x, y); |
36 |
repaint(); |
37 |
} |
38 |
|
39 |
//
do-nothing methods |
40 |
public void mouseReleased(MouseEvent event) {} |
41 |
public void mouseClicked(MouseEvent event) {} |
42 |
public void mouseEntered(MouseEvent event) {} |
43 |
public void mouseExited(MouseEvent event) {} |
44 |
} |
45 |
|
46 |
MouseListener listener = new MousePressListener(); |
47 |
addMouseListener(listener); |
48 |
} |
49 |
|
50 |
public void paintComponent(Graphics g) |
51 |
{ |
52 |
super.paintComponent(g); |
53 |
Graphics2D g2 = (Graphics2D)g; |
54 |
g2.draw(box); |
55 |
} |
56 |
|
57 |
private Rectangle box; |
58 |
private static final int BOX_X = 100; |
59 |
private static final int BOX_Y = 100; |
60 |
private static final int BOX_WIDTH = 20; |
61 |
private static final int BOX_HEIGHT = 30; |
62 |
|
63 |
private static final int PANEL_WIDTH = 300; |
64 |
private static final int PANEL_HEIGHT = 300; |
65 |
} |