1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| /** 以 FlowLayout 布局 JPanel(1)*/
JPanel p1 = new JPanel(new FlowLayout()); // 默认组件从居中开始
// 加入"BackSpace"和"Clear"JButton
p1.add(backButton);
p1.add(clearButton);
/** 以 GridLayout 布局 JPanel(2)*/
JPanel p2 = new JPanel(new GridLayout(2, 1)); // 放置 2 行,每行 1 个组件
// 加入显示结果的 JTextField 和 JPanel(1)
p2.add(displayField);
p2.add(p1);
/** 以 GridLayout 布局 JPanel(3)*/
JPanel p3 = new JPanel(new GridLayout(4, 5)); // 放置 4 行,每行 5 个组件
String buttonStr = "789/A456*B123-C0.D+=";
for (int i = 0; i < buttonStr.length(); i++)
this.addButton(p3, buttonStr.substring(i, i + 1));
//addButton 方法
private void addButton(Container c, String s)
{
JButton b = new JButton(s);
if (s.equals("A"))
b.setText("sqrt");
else if (s.equals("B"))
b.setText("1/x");
else if (s.equals("C"))
b.setText("%");
else if (s.equals("D"))
b.setText("+/-");
b.setForeground(Color.blue);
c.add(b);
b.addActionListener(this);
}
/** 以 BorderLayout 布局 JApplet*/
this.setLayout(new BorderLayout());
this.add(p2, "North");
this.add(p3, "Center");
|