长方形(GUI)

        求长方形的面积和周长,GUI。

运行结果:

                                    

 

代码:

  1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class Test
6 {
7 public static void main(String[] args)
8 {
9 new OblongGUI();
10 }
11 }
12
13 class OblongGUI extends JFrame implements ActionListener
14 {
15 private Oblong myOblong = new Oblong(0,0);
16
17 private JLabel lengthLabel = new JLabel("Length");
18 private JTextField lengthField = new JTextField(5);
19
20 private JLabel heightLabel = new JLabel("Height");
21 private JTextField heightField = new JTextField(5);
22
23 private JButton calcButton = new JButton("Calculate");
24 private JTextArea displayArea = new JTextArea(2,20);
25
26 public OblongGUI()
27 {
28 setTitle("Oblong GUI");// Title
29 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 setLayout(new FlowLayout());//Layout
31 /* 设置布局后,就开始添加组件 ,一共六个 */
32 add(lengthLabel);
33 add(lengthField);
34 add(heightLabel);
35 add(heightField);
36 add(calcButton);
37 add(displayArea);
38
39 /* 设置大小和位置 */
40 setSize(240,135);
41 setLocation(300,200);
42 /* 让按钮能够Listen事件,从而采取适当行动 */
43 calcButton.addActionListener(this);
44
45 setVisible(true);
46 }
47
48 /* 事件处理器 */
49 public void actionPerformed(ActionEvent e)
50 {
51 String lengthEntered = lengthField.getText();
52 String heightEntered = heightField.getText();
53
54 if(lengthEntered.length()==0||heightEntered.length()==0)
55 displayArea.setText("Length and height must be entered");
56 else
57 {
58 myOblong.setLenght(Double.parseDouble(lengthEntered));
59 myOblong.setHeight(Double.parseDouble(heightEntered));
60 displayArea.setText("The area is "+
61 myOblong.calculateArea()+"\n"+"The perimeter is"
62 +myOblong.calculatePerimeter());
63
64 }
65 }
66
67 }
68
69 class Oblong
70 {
71 private double length;
72 private double height;
73
74 public Oblong(double a,double b)
75 {
76 length = a; height = b ;
77 }
78
79 public double getLength()
80 {
81 return length;
82 }
83 public double getHeight()
84 {
85 return height;
86 }
87
88 public void setLenght(double a)
89 {
90 length = a;
91 }
92 public void setHeight(double b)
93 {
94 height = b;
95 }
96
97 public double calculateArea()
98 {
99 return length*height;
100 }
101
102 public double calculatePerimeter()
103 {
104 return 2*(length + height);
105 }
106 }

 

posted @ 2012-03-05 19:56  开开甲  阅读(254)  评论(0编辑  收藏  举报