仿照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);
	}
}
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值