天天看点

计算器代码

import java.awt.*;//AWT核心包

import java.awt.event.*;//提供事件类和监听器

public class Counter extends Frame implementsActionListener

{

TextField t=newTextField("");//文本框

Panel p1=newPanel();//new一个panel,用于存放数字键和符号键。

Panel p2=newPanel();//new一个panel,用于存放开方、平方、和清除键。

Button[] b=newButton[10];//实例化Button对象

Button bAdd=newButton("加");

Button bSub=newButton("减");

Button bMul=newButton("乘以");

Button bPoint=newButton(".");

Button bDiv=newButton("除以");

Button bEqual=newButton("等於");

Button bSqrt=newButton("开方");

Button bPow=newButton("平方");

Button bNull=newButton("清除");

Stringstr1="";     //str1和str2存放两个输入的数

Stringstr2="";

Stringoperator=null;   //存放加减乘除以及开平方的符号

booleanfirst=true;    //检验输入的是否为第一个数

intcountOper=0;    //累计输入符号的个数,连加连减等操作中会用到

doubleresult=0.0;    //暂存结果

double num1=0.0,num2=0.0;  //两个输入的数做运算时转化为double存放

booleanerror=false;   //检验除数是否为0

//构造方法

public Counter()

 Frame s=newFrame("计算器");//创建Frame

 for(inti=0;i<10;i++)//利用for循环将数字键添加进p1中

 {

  b[i]=newButton(String.valueOf(i));

  p1.add(b[i]);

 b[i].setActionCommand("number");

 b[i].setForeground(new Color(150,20,20));

 b[i].addActionListener(this);//调用addActionListener()方法注册事件监听器

 }

 p1.add(bPoint);

bPoint.setActionCommand("number");

 p1.add(bAdd); //数字键,符号键放置在panel的p1中

 p1.add(bSub);

 p1.add(bMul);

 p1.add(bDiv);

 p1.add(bEqual);

 p2.add(bSqrt);//开方键,平方键,清除键放置在panel的p2中

p2.add(bPow);    

 p2.add(bNull);

bAdd.setActionCommand("oper");

bSub.setActionCommand("oper");

bMul.setActionCommand("oper");

 bDiv.setActionCommand("oper");

bAdd.setForeground(Color.red);//为组键设计颜色

bSub.setForeground(Color.red);

bMul.setForeground(Color.red);

bDiv.setForeground(Color.red);

bPoint.setForeground(Color.black);

bEqual.setForeground(Color.red);

bSqrt.setForeground(Color.blue);

bPow.setForeground(Color.blue);

bNull.setForeground(Color.blue);

bAdd.addActionListener(this);//调用addActionListener()方法注册事件监听器

bSub.addActionListener(this);

bMul.addActionListener(this);

bDiv.addActionListener(this);

bPoint.addActionListener(this);

bEqual.addActionListener(this);

bSqrt.addActionListener(this);

bPow.addActionListener(this);

bNull.addActionListener(this);

 p1.setLayout(newGridLayout(4,4,5,5));//网格布局管理器,把容器根据行数和列数分成同样大小的单元,

                                    //每个单元可容纳一个组件,并且此组件会填满网格单元,不能控

                                    //制其占据网格的大小。4、4为网格的行、列数。5、5为组建之间的

                                    //间距

 p2.setLayout(newFlowLayout());//用FlowLayout布局管理器将组建默认剧中排放,默认间隙为5个像素

add(t,"North");      //frame的north放置输入框,panel放置在center和south

add(p1,"Center");//将p1添加到Center中

add(p2,"South");//将p2添加到South中

setLocation(400,200);//设计按钮尺寸

setSize(200,200);//设计窗口尺寸

 setBackground(newColor(20,200,10));//设置Frame的背景,默认为白色

setVisible(true);//设置Frame设置为可见

addWindowListener(new WindowAdapter(){  //关闭窗口功能

  public voidwindowClosing(WindowEvent e)

  {

   System.exit(0);

  }

 });

}

//实现接口ActionListener

public voidactionPerformed(ActionEvent e)

 Buttontemp=(Button)e.getSource();

if(e.getActionCommand().equals("number"))

  if(first)

  str1=str1+temp.getLabel();

  t.setText(str1);//将输入的str1显示在文本框中

  else

  str2=str2+temp.getLabel();

  t.setText(str2);//将输入的str2显示在文本框中

 elseif(e.getActionCommand().equals("oper"))

 if(str1=="")    //如果还没有输入数就点击运算符执行if

   countOper=0;//若此,则将计数清零

   first=true;

   countOper++;//计算输入符号的个数

  if(countOper>1)//若输入的符号个数多余一个,则可以进行计算

   {

    getResult();

   }

  operator=temp.getLabel();//存放加减乘除以及开方、平方的符号

   first=false;

 elseif(e.getActionCommand().equals("开方"))

   doubled=Math.sqrt(Double.parseDouble(str1));

  str1=String.valueOf(d);//将计算出来的结果再次传给str1,为连计算准备

  t.setText(String.valueOf(d));//将计算出来的结果传至文本框中

   first=false;//置为false,即已输入第一个数

  }  

 elseif(e.getActionCommand().equals("平方"))

   doublef=Math.pow(Double.parseDouble(str1),2);

  str1=String.valueOf(f);

  t.setText(String.valueOf(f));

 elseif(e.getActionCommand().equals("清除"))

 str1="";//清空

 str2="";

 t.setText("");//将文本框清空

  countOper=0;//将按键计数器清零

  first=true;

  error=false;

 elseif(e.getActionCommand().equals("等於"))

  if((str1=="")||(str2==""))   //两个数没有输全就点击等号,执行if

   countOper=0;//将按键计数器清零

 else

   getResult();

   countOper=0;

//运算结果的方法

public voidgetResult()

num1=Double.parseDouble(str1);

num2=Double.parseDouble(str2);

if(operator.equals("加"))

 result=num1+num2;

 elseif(operator.equals("减"))

 result=num1-num2;

 elseif(operator.equals("乘以"))

 result=num1*num2;

 elseif(operator.equals("除以"))

 if(num2==0.0)    //除数为0的处理方法

   error=true;

  result=num1/num2;

 if(error)

 t.setText("error");

 t.setText(String.valueOf(result));

 str1=String.valueOf(result);  //运算后把结果放入str1中,str2清空,为连加连减等操作做准备

//主方法

public static voidmain(String[] args)

 new Counter();//创建一个对象"计算器"

import  java.awt.*;  

 import   java.awt.event.*;  

 import   javax.swing.*;  

 class   CalculatorPanel   extends  JPanel  

      implements   ActionListener  

 {     public  CalculatorPanel()  

       {     setLayout(new   BorderLayout());  

            display   =   new  JTextField("0");  

            display.setEditable(false);  

             add(display,  "North");  

            JPanel   p   =  new   JPanel();  

            p.setLayout(new  GridLayout(4,   4));  

            String   buttons   =  "789/456*123-0.=+";  

            for   (int   i  =   0;   i   <   buttons.length();   i++)    

                  addButton(p,  buttons.substring(i,   i   +  1));              

            add(p,   "Center");  

       }  

      private   void   addButton(Container   c,  String   s)  

       {     JButton  b   =   new  JButton(s);  

            c.add(b);  

            b.addActionListener(this);  

       public   void  actionPerformed(ActionEvent  evt)  

       {     String  s   =   evt.getActionCommand();  

            if   ('0'   <=  s.charAt(0)   &&   s.charAt(0)  <=   '9'    

                  ||   s.equals("."))  

            {     if   (start)  display.setText(s);  

                  else  display.setText(display.getText()  +   s);  

                  start   =   false;  

            }  

            else  

            {     if   (start)  

                  {     if   (s.equals("-"))    

                        {   display.setText(s);   start  =   false;   }  

                         else   op  =   s;  

                  }  

                  else  

                  {    calculate(Double.parseDouble(display.getText()));  

                        op   =   s;  

                        start   =   true;  

       public   void  calculate(double   n)  

       {     if  (op.equals("+"))  arg   +=   n;  

            else   if   (op.equals("-"))   arg  -=   n;  

             else   if  (op.equals("*"))  arg   *=   n;  

            else   if   (op.equals("/"))   arg  /=   n;  

            else   if   (op.equals("="))   arg  =   n;  

            display.setText(""  +   arg);  

       private   JTextField  display;  

      private   double   arg  =   0;  

      private   String   op  =   "=";  

      private   boolean   start  =   true;  

 }  

 public   class  CalculatorApplet   extends   JApplet  

 {     public  void   init()  

       {     Container  contentPane   =   getContentPane();  

            contentPane.add(new  CalculatorPanel());