java项目实战-计算器(页面布局学习 添加事件)

package com.ten.jiauanqi;

import java.awt.*;
import java.awt.event.*;

public class Calculator extends WindowAdapter{
	//定义3个面板
	Panel p1=new Panel();
	Panel p2=new Panel();
	Panel p3=new Panel();
	TextField txt;//创建文本框对象
	private Button[] b=new Button[17];//创建按钮数组
	private String ss[]={"7","8","9","+","4","5","6","-","1","2","3","*","清空","0","=","/","关闭"};
	static double a;//创建double类型变量
	static String s,str;//创建String类型变量
	
	public static void main(String args[])
	{
		(new Calculator()).frame();
	}
	
	public void frame()
	{
		Frame fm=new Frame("计算器");
		for(int i=0;i<=16;i++){
			b[i] = new Button(ss[i]);//为按钮数组赋值
		}
		
		for(int i=0;i<=15;i++)
		{
			p2.add(b[i]);
		}
		
		b[16].setBackground(Color.yellow);//设置按钮背景色为黄色
		//创建和设置文本框
		txt= new TextField(15);
		txt.setEditable(false);
		
		for(int i=0;i<=16;i++)
		{
			b[i].addActionListener(new buttonlistener());//为按钮添加监听器
		}
		
		b[16].addActionListener(new close());//为按钮添加关闭监听器
		
		fm.addWindowListener(this);
		fm.setBackground(Color.red);
		p1.setLayout(new BorderLayout());
		p1.add(txt,"North");
		p2.setLayout(new GridLayout(4,4));
		p3.setLayout(new BorderLayout());
		p3.add(b[16]);
		
		//添加各个面板到窗口上
		fm.add(p1,"North");
		fm.add(p2,"Center");
		fm.add(p3,"South");
		fm.pack();
		fm.setVisible(true);
	}
	
	public void windowClosing(WindowEvent e)
	{
		System.exit(0);
	}


	//编写事件监听器
	class buttonlistener implements ActionListener{
		public void actionPerformed(ActionEvent e)
		{
			Button btn=(Button)e.getSource();//获取事件按钮
			if(btn.getLabel()=="=")
			{
				jisuan();
				str=String.valueOf(a);
				txt.setText(str);
				s="";				
			}else if(btn.getLabel()=="+")
			{
				jisuan();
				txt.setText("");
				s="+";
			}else if(btn.getLabel()=="-")
			{
				jisuan();
				txt.setText("");
				s="-";
			}else if(btn.getLabel()=="*")
			{
				jisuan();
				txt.setText("");
				s="*";
			}else if(btn.getLabel()=="/")
			{
				jisuan();
				txt.setText("");
				s="/";
			}else{
				txt.setText(txt.getText()+btn.getLabel());
				if(btn.getLabel()=="清空")
					txt.setText("");
			}
		}
		
		public void jisuan()
		{
			if(s=="+")
			{
				a+=Double.parseDouble(txt.getText());
			}else if(s=="-")
			{
				a-=Double.parseDouble(txt.getText());
			}else if(s=="*")
			{
				a*=Double.parseDouble(txt.getText());
			}else if(s=="/")
			{
				a/=Double.parseDouble(txt.getText());
			}else{
				a=Double.parseDouble(txt.getText());
			}
		}
	}
	
	class close implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			System.exit(0);
		}
	}

}

效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值