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.ImageIcon; |
8 |
import javax.swing.JButton; |
9 |
import javax.swing.JFrame; |
10 |
import javax.swing.JLabel; |
11 |
import javax.swing.JPanel; |
12 |
import javax.swing.JTextField; |
13 |
|
14 |
/** |
15 |
This applet lets the user move a rectangle by specifying |
16 |
the x- and y-position of the top left corner. |
17 |
*/ |
18 |
public class ButtonApplet extends Applet |
19 |
{ |
20 |
public ButtonApplet() |
21 |
{ |
22 |
// the rectangle that the paint method draws |
23 |
box = new Rectangle(BOX_X, BOX_Y, |
24 |
BOX_WIDTH, BOX_HEIGHT); |
25 |
|
26 |
// the text fields for entering the x- and y-coordinates |
27 |
final JTextField xField = new JTextField(5); |
28 |
final JTextField yField = new JTextField(5);; |
29 |
|
30 |
// the button to move the rectangle |
31 |
JButton moveButton = new JButton("Move", |
32 |
new ImageIcon("hand.gif")); |
33 |
|
34 |
class MoveButtonListener implements ActionListener |
35 |
{ |
36 |
public void actionPerformed(ActionEvent event) |
37 |
{ |
38 |
int x = Integer.parseInt(xField.getText()); |
39 |
int y = Integer.parseInt(yField.getText()); |
40 |
box.setLocation(x, y); |
41 |
repaint(); |
42 |
} |
43 |
}; |
44 |
|
45 |
ActionListener listener = new MoveButtonListener(); |
46 |
moveButton.addActionListener(listener); |
47 |
|
48 |
// the labels for labeling the text fields |
49 |
JLabel xLabel = new JLabel("x = "); |
50 |
JLabel yLabel = new JLabel("y = "); |
51 |
|
52 |
// the panel for holding the user interface components |
53 |
JPanel panel = new JPanel(); |
54 |
|
55 |
panel.add(xLabel); |
56 |
panel.add(xField); |
57 |
panel.add(yLabel); |
58 |
panel.add(yField); |
59 |
panel.add(moveButton); |
60 |
|
61 |
// the frame for holding the component panel |
62 |
JFrame frame = new JFrame(); |
63 |
frame.setContentPane(panel); |
64 |
frame.pack(); |
65 |
frame.show(); |
66 |
} |
67 |
|
68 |
public void paint(Graphics g) |
69 |
{ |
70 |
Graphics2D g2 = (Graphics2D)g; |
71 |
g2.draw(box); |
72 |
} |
73 |
|
74 |
private Rectangle box; |
75 |
private static final int BOX_X = 100; |
76 |
private static final int BOX_Y = 100; |
77 |
private static final int BOX_WIDTH = 20; |
78 |
private static final int BOX_HEIGHT = 30; |
79 |
} |