仿照Windows的计算器,编写一个简易的计算器程序,实现加、减、乘、除等运算。

仿照Windows的计算器,编写一个简易的计算器程序,实现加、减、乘、除等运算。
偷懒了很多,将就着用吧:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class CalculateFrameDemo {
	public static void main(String[] args) {
		CalculateFrame frm = new CalculateFrame();
		frm.setVisible(true);
	}
}

class CalculateFrame extends JFrame{
	private JButton Buttonadd;
	private JButton Buttonsub;
	private JButton Buttonmul;
	private JButton Buttondiv;
	private JButton Buttonequ;
	private JTextField text1;
	private JTextField text2;
	public int a,b,c,Flag;
	CalculateFrame(){
		setTitle("网格布局器示例");
		setSize(500,400);
		setLocation(300,200);
		text1 = new JTextField(20) ;
		text2 = new JTextField(20) ;
		text1.setBounds(200,20,100,50);
		text2.setBounds(250,100,100,50);
		Buttonadd = new JButton("+");
    	Buttonsub = new JButton("-");
    	Buttonmul = new JButton("*");
    	Buttondiv = new JButton("/");
    	Buttonequ = new JButton("=");
		setLayout(new FlowLayout());
		Buttonadd.addActionListener(new ActionListener(){  //添加监听器+
			public void actionPerformed(ActionEvent e){
				String s = text1.getText();
				Flag=1;//设定标志位
				a = Integer.parseInt(s);//转成数字保存
				text1.setText("");//清空
			}
		});
		Buttonsub.addActionListener(new ActionListener(){  //添加监听器-
			public void actionPerformed(ActionEvent e){
				String s = text1.getText();
				Flag=2;//设定标志位
				a = Integer.parseInt(s);//转成数字保存
				text1.setText("");//清空
			}
		});
		Buttonmul.addActionListener(new ActionListener(){  //添加监听器*
			public void actionPerformed(ActionEvent e){
				String s = text1.getText();
				Flag=3;//设定标志位
				a = Integer.parseInt(s);//转成数字保存
				text1.setText("");//清空
			}
		});
		Buttondiv.addActionListener(new ActionListener(){  //添加监听器/
			public void actionPerformed(ActionEvent e){
				String s = text1.getText();
				Flag=4;//设定标志位
				a = Integer.parseInt(s);//转成数字保存
				text1.setText("");//清空
			}
		});
		
		Buttonequ.addActionListener(new ActionListener(){  //添加监听器=
			public void actionPerformed(ActionEvent e){
				String s = text1.getText();
				b = Integer.parseInt(s);//转成数字保存
				text1.setText("");//清空
				if(Flag == 1) c=a+b;
				else if(Flag == 2) c=a-b;
				else if(Flag == 3) c=a*b;
				else if(Flag == 4) c=a/b;
				text2.setText(""+c);
			}
		});
			
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//setLayout(new GridLayout(5,3,5,5)); //设置框架使用5行3列的网格布局器//水平间距与垂直间距为10
		add(text1);
		add(text2);								  
        
    	add(Buttonadd);
    	add(Buttonsub);
    	add(Buttonmul);
    	add(Buttondiv);
    	add(Buttonequ);
	}
}

你可能感兴趣的:(#,Java)