previous | start | next

File RectangleFrame.java

1 import java.awt.BorderLayout;
2 import java.awt.event.ActionEvent;
3 import java.awt.event.ActionListener;
4 import javax.swing.JButton;
5 import javax.swing.JFrame;
6 import javax.swing.JLabel;
7 import javax.swing.JPanel;
8 import javax.swing.JTextField;
9
10 /**
11     This frame contains a panel that displays a rectangle
12     and a panel of text fields to specify the rectangle position.
13 */
14 public class RectangleFrame extends JFrame
15 {
16    /**
17        Constructs the frame.
18     */
19    public RectangleFrame()
20    {
21       // the panel that draws the rectangle
22       rectPanel = new RectanglePanel();
23
24       // add panel to content Pane
25       getContentPane().add(rectPanel, BorderLayout.CENTER);
26
27       createControlPanel();
28
29       pack();
30    }
31
32    /**
33        Creates the control panel with the text fields
34        at the bottom of the frame.
35     */
36    private void createControlPanel()
37    {
38       // the text fields for entering the x- and y-coordinates
39       final JTextField xField = new JTextField(5);
40       final JTextField yField = new JTextField(5);;
41
42       // the button to move the rectangle
43       JButton moveButton = new JButton("Move");
44
45       class MoveButtonListener implements ActionListener
46       {
47          public void actionPerformed(ActionEvent event)
48          {
49             int x = Integer.parseInt(xField.getText());
50             int y = Integer.parseInt(yField.getText());
51             rectPanel.setLocation(x, y);
52          }
53       };
54
55       ActionListener listener = new MoveButtonListener();
56       moveButton.addActionListener(listener);
57
58       // the labels for labeling the text fields
59       JLabel xLabel = new JLabel("x = ");
60       JLabel yLabel = new JLabel("y = ");
61
62       // the panel for holding the user interface components
63       JPanel controlPanel = new JPanel();
64
65       controlPanel.add(xLabel);
66       controlPanel.add(xField);
67       controlPanel.add(yLabel);
68       controlPanel.add(yField);
69       controlPanel.add(moveButton);
70
71       getContentPane().add(controlPanel, BorderLayout.SOUTH);
72    }
73
74    private RectanglePanel rectPanel;
75 }
76
77
78
79
80


previous | start | next