1 |
import java.applet.Applet; |
2 |
import java.awt.Graphics; |
3 |
import java.awt.Graphics2D; |
4 |
import java.awt.Rectangle; |
5 |
import java.awt.event.ActionEvent; |
6 |
import java.awt.event.ActionListener; |
7 |
import javax.swing.JButton; |
8 |
import javax.swing.JFrame; |
9 |
import javax.swing.JPanel; |
10 |
|
11 |
/** |
12 |
This applet lets the user move a rectangle by clicking |
13 |
on buttons labeled "Left", "Right", "Up", and "Down". |
14 |
*/ |
15 |
public class ButtonApplet extends Applet |
16 |
{ |
17 |
public ButtonApplet() |
18 |
{ |
19 |
// the rectangle that the paint method draws |
20 |
box = new Rectangle(BOX_X, BOX_Y, |
21 |
BOX_WIDTH, BOX_HEIGHT); |
22 |
|
23 |
// the panel for holding the user interface components |
24 |
JPanel panel = new JPanel(); |
25 |
|
26 |
panel.add(makeButton("Left", -BOX_WIDTH, 0)); |
27 |
panel.add(makeButton("Right", BOX_WIDTH, 0)); |
28 |
panel.add(makeButton("Up", 0, -BOX_HEIGHT)); |
29 |
panel.add(makeButton("Down", 0, BOX_HEIGHT)); |
30 |
|
31 |
// the frame for holding the component panel |
32 |
JFrame frame = new JFrame(); |
33 |
frame.setContentPane(panel); |
34 |
frame.pack(); |
35 |
frame.show(); |
36 |
} |
37 |
|
38 |
public void paint(Graphics g) |
39 |
{ |
40 |
Graphics2D g2 = (Graphics2D)g; |
41 |
g2.draw(box); |
42 |
} |
43 |
|
44 |
/** |
45 |
Makes a button that moves the box. |
46 |
@param label the label to show on the button |
47 |
@param dx the amount by which to move the box in x-direction |
48 |
when the button is clicked |
49 |
@param dy the amount by which to move the box in y-direction |
50 |
when the button is clicked |
51 |
@return the button |
52 |
*/ |
53 |
public JButton makeButton(String label, final int dx, |
54 |
final int dy) |
55 |
{ |
56 |
JButton button = new JButton(label); |
57 |
|
58 |
class ButtonListener implements ActionListener |
59 |
{ |
60 |
public void actionPerformed(ActionEvent event) |
61 |
{ |
62 |
box.translate(dx, dy); |
63 |
repaint(); |
64 |
} |
65 |
}; |
66 |
|
67 |
ButtonListener listener = new ButtonListener(); |
68 |
button.addActionListener(listener); |
69 |
return button; |
70 |
} |
71 |
|
72 |
private Rectangle box; |
73 |
private static final int BOX_X = 100; |
74 |
private static final int BOX_Y = 100; |
75 |
private static final int BOX_WIDTH = 20; |
76 |
private static final int BOX_HEIGHT = 30; |
77 |
} |