编写一个应用程序,有一个标题为“计算”的窗口,窗口的布局为FlowLayout布局。设计4个按钮,分别命名为“加”、“差”、“积”、“除”,另外,窗口中还有3个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Exercise1 extends JFrame implements ActionListener{
private JPanel p1 = new JPanel(); //创建面板
private JPanel p2 = new JPanel(); //创建面板
private JTextField t1; //文本框1用来显示输入信息
private JTextField t2;
private JTextField t3;
StringBuffer str;//输入的字符串
JButton[] b=new JButton[10];
JButton b1,b2,b3,b4,b6;//+,-,*,%,清零
double x,y;
int n;
public Exercise1() {
super("190702940115"); //个人标识
setSize(500,200); //设置窗口大小
setLocationRelativeTo(null); //显示到中间
Container c = getContentPane(); //创建内容面板对象
t1 = new JTextField(15);
t2 = new JTextField(15);
t3 = new JTextField(15);
t1.setEditable(true);
t2.setEditable(true);
t3.setEditable(false); //只能显示,不能编辑
p2.add(t1);
p2.add(t2);
p2.add(t3); //添加文本框到面板
p2.setLayout(new GridLayout(1,4)); //把面扳布局为2行2列
str=new StringBuffer();
b1=new JButton("+");
b2=new JButton("-");
b3=new JButton("*");
b4=new JButton("/");
b6=new JButton("delete");
//添加到面板
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(b4);
p1.add(b6);
p1.setLayout(new GridLayout(1,5));
//注册监听器
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b6.addActionListener(this);
//将内容添加到面板上然后添加到容器里
c.add(p2);
c.add(p1);
c.setLayout(new FlowLayout()); //设置为顺序布局
//设置窗口关闭动作
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口关闭动作
setVisible(true); //设置为可见
setResizable(false); //禁止调整框架大小
}
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("unused")
Exercise1 calculate=new Exercise1();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==b6){
t1.setText(null);
t2.setText(null);
t3.setText(null);//清空
t1.setHorizontalAlignment(JTextField.LEFT);
t2.setHorizontalAlignment(JTextField.LEFT);
t3.setHorizontalAlignment(JTextField.LEFT);//左对齐
str.setLength(0);
}
//Double.parseDouble 将字符串转化为double类型
//t1.getText().trim() 获取字符保存后并且清除
else if (e.getSource()==b1)//加法运算
{
x=Double.parseDouble(t1.getText().trim());
str.setLength(0);
y=Double.parseDouble(t2.getText().trim());;
t3.setText(""+(x+y));
}else if(e.getSource()==b2)//减法运算
{
x=Double.parseDouble(t1.getText().trim());
str.setLength(0);
y=Double.parseDouble(t2.getText().trim());;
t3.setText(""+(x-y));
}else if(e.getSource()==b3)//乘法运算
{
x=Double.parseDouble(t1.getText().trim());
str.setLength(0);
y=Double.parseDouble(t2.getText().trim());;
t3.setText(""+(x*y));
}else if(e.getSource()==b4)//除法运算
{
x=Double.parseDouble(t1.getText().trim());
str.setLength(0);
y=Double.parseDouble(t2.getText().trim());;
t3.setText(""+(x/y));
}
}
}



