加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java实现计算器的基本功能

(2010-01-04 22:18:42)
标签:

杂谈

分类: 专业探讨

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener
{
 JFrame frame;
 private JButton[] buttons,operations;
  private String[] bu={"0","1","2","3","4","5","6","7","8","9"};
 private String[] op={"+","-","*","/","=",".","sqrt","+/-","backspace","ce","c","sin","1/x"};
 private TextField kongbai=new TextField(); //K1
 
    JMenuBar mainMenu;
    JMenuItem copy,paste,exit,about,me;
   
    Container con;
    JTextField text;
    String copycontent="";
    boolean clickable=true,clear=true;
    int all=0;
    double qian; //当前所到的数字
    String fuhao;// 当前得到的符号
    int first=1;

 public Calculator()
 {
  super("Java计算器——刘超陈哲制作");
  setSize(400,300);
        setLocation(250,200);
        JLabel label=new JLabel("result:");
        text=new JTextField(30);
        text.setEnabled(false);
        text.setText("0.");
        text.setHorizontalAlignment(JTextField.RIGHT);//从右到左

  JPanel con1=new JPanel();
        JPanel con2=new JPanel();
        JPanel con3=new JPanel();

        con=getContentPane();
        con.add(con1,"North");
        con.add(con2,"Center");
        con.add(con3,"South");

  con1.setLayout(new FlowLayout(FlowLayout.LEFT));
       
    con2.setLayout(new GridLayout(4,5,1,1));  //四行、五列
  con3.setLayout(new GridLayout(1,3,1,1));

  buttons=new JButton[10];
  for (int i=0;i<10 ;i++ )
  {
   buttons[i]=new JButton(bu[i]);
   buttons[i].addActionListener(this);
  }
  operations=new JButton[13];
  for (int j=0;j<13 ;j++ )
  {
   operations[j]=new JButton(op[j]);
   operations[j].addActionListener(this);
  }
  operations[0].setForeground(Color.red);
  operations[1].setForeground(Color.red);
  operations[2].setForeground(Color.red);
  operations[3].setForeground(Color.red);
  operations[4].setForeground(Color.red);
    operations[8].setForeground(Color.red);
  operations[9].setForeground(Color.red);
    operations[10].setForeground(Color.red);
  operations[6].setForeground(Color.blue);
  operations[11].setForeground(Color.blue);
  operations[12].setForeground(Color.blue);

        JTextField t3=new JTextField(30);
        con1.add(label);
        con1.add(text);
        text.setEditable(true);//好像可有可无,不起作用
        text.setBackground(new Color(255, 255, 255));

    con2.add(buttons[7]);
  con2.add(buttons[8]);
  con2.add(buttons[9]);
  con2.add(operations[3]);
  con2.add(operations[6]);
  con2.add(buttons[4]);
  con2.add(buttons[5]);
  con2.add(buttons[6]);
  con2.add(operations[2]);
  con2.add(operations[12]);
  con2.add(buttons[1]);
  con2.add(buttons[2]);
  con2.add(buttons[3]);
  con2.add(operations[1]);
  con2.add(operations[11]);
  con2.add(buttons[0]);
  con2.add(operations[5]);
  con2.add(operations[7]);
  con2.add(operations[0]);
  con2.add(operations[4]);
  kongbai.setEnabled(false);
  con3.add(kongbai);
  con3.add(operations[8]);
  con3.add(operations[9]);
  con3.add(operations[10]);
  
        mainMenu = new JMenuBar();
        setJMenuBar(mainMenu);
        JMenu editMenu = new JMenu("编辑"); 
        JMenu helpMenu = new JMenu("帮助");
        mainMenu.add(editMenu);
        mainMenu.add(helpMenu);
 
        copy = new JMenuItem(" 复制");
        paste = new JMenuItem(" 粘贴");
        exit=new JMenuItem("退出");
        KeyStroke copyks=KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK);
        copy.setAccelerator(copyks);//设置退出菜单选项加上快捷键
        KeyStroke pasteks=KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK);
        paste.setAccelerator(pasteks);//设置退出菜单选项加上快捷键
        editMenu.add(copy);
        editMenu.add(paste);
        editMenu.add(exit);
        copy.addActionListener(this);
        paste.addActionListener(this);
        exit.addActionListener(this);
 
        about = new JMenuItem(" 关于计算器");
        me = new JMenuItem(" 作者主页");
        helpMenu.add(about); 
        helpMenu.add(me);
        about.addActionListener(this);
        me.addActionListener(this);
        addWindowListener(new WindowDestroyer());//结束窗口
 }


 public void actionPerformed(ActionEvent e)//设置按钮的动作
    {
        if(first==1)
           text.setText("");
           first=0;//第一次把文本框0.清空
        Object temp = e.getSource();
  String str=text.getText();
        if(temp==copy) //设置copy的动作
          {
            copycontent = text.getText();
          }
        if(temp==paste) //设置paste的动作
          {
            text.setText(text.getText()+copycontent);
          }
        if (temp==exit)//设置exit的动作
          {
         System.exit(0);
          }
         if(temp==about)//设置about的动作
          {
            JOptionPane.showMessageDialog(frame,"              Java计算器\n刘超(学号:320070925181)\n陈哲(学号:320070924821)\n            07信息安全班\n                兰州大学\n      信息科学与工程学院","关于计算器",JOptionPane.INFORMATION_MESSAGE); ;
          }
         if(temp==me)//设置me动作
          {
            try
            {
              Process p = Runtime.getRuntime().exec("explorer http://blog.sina.com.cn/birdyard");
            }
            catch(Exception eeee)
            {
              System.out.println("打开指定网页出错");   
            }
          }

         if(temp==operations[8])//backspace
          {//退格
            String s = text.getText();
            text.setText("");
            for (int i = 0; i < s.length() - 1; i++)
             {
               char a = s.charAt(i);
               text.setText(text.getText() + a);
             }
          }
         if (temp==operations[9]) //ce
          {
            text.setText("0.");
            clear=true;
            first=1;
           }
         if (temp==operations[10])  //c
          {
            text.setText("0.");   ;
            clear=true;
            first=1;
          }
         if(temp==buttons[0])
         
            if(clear==false)//判断是否点击了符号位
               text.setText("");
               text.setText(text.getText()+"0");
               clear=true;
          }
         if(temp==buttons[1])
           
            if(clear==false)
               text.setText("");
               text.setText(text.getText()+"1");
               clear=true;//第二次不在清空(前二句)
          }
         if(temp==buttons[2])
           
            if(clear==false)
               text.setText("");
               text.setText(text.getText()+"2");
               clear=true;
         
         if(temp==buttons[3])
           
            if(clear==false)
               text.setText("");
               text.setText(text.getText()+"3");
               clear=true;
          }
         if(temp==buttons[4])
           
           if(clear==false)
              text.setText("");
              text.setText(text.getText()+"4");
              clear=true;
          }
         if(temp==buttons[5])
          {
           if(clear==false)
              text.setText("");
              text.setText(text.getText()+"5");
              clear=true;
          }
         if(temp==buttons[6])
          {
            if(clear==false)
               text.setText("");
               text.setText(text.getText()+"6");
               clear=true;
          }
         if(temp==buttons[7])
          {
            if(clear==false)
               text.setText("");
               text.setText(text.getText()+"7");
               clear=true;
          }
         if(temp==buttons[8])
          {
            if(clear==false)
              text.setText("");
              text.setText(text.getText()+"8");
              clear=true;
          }
         if(temp==buttons[9])
          {
           if(clear==false)
              text.setText("");
              text.setText(text.getText()+"9");
              clear=true;
          }
         
          if(temp==operations[5])
          {
          String nul=text.getText();
          String c;
          if(nul==null) 
              //text.setText("0.");
              System.out.println("input");
          else
          {
              int len=nul.length();
              char ch=nul.charAt(len-1);
              if(ch!='.')
              {
               c=nul.concat(".");
               text.setText(c);
              }
          
          }
         
         try
         {
          if(temp==operations[0])//+
           {//加法
            qian=Double.parseDouble(text.getText());
            fuhao="+";
            clear=false;
            }
           if(temp==operations[1])//-
            {
             qian=Double.parseDouble(text.getText());
             fuhao="-";
             clear=false;
             }
            if(temp==operations[2])//*
             {
              qian=Double.parseDouble(text.getText());
              fuhao="*";
              clear=false;  
             }
            if(temp==operations[3])// /
             {
              qian=Double.parseDouble(text.getText());
              fuhao="/";
              clear=false;    
             }
            if(temp==operations[4])//==
             {
              double ss=Double.parseDouble(text.getText());
              text.setText("");
              if(fuhao=="+")
                 text.setText(qian+ss+"");
              if(fuhao=="-")
                 text.setText(qian-ss+"");
              if(fuhao=="*")
                 text.setText(qian*ss+"");
              if(fuhao=="/")
                 text.setText(qian/ss+"");
              clear=false;//要清空前一次的数据
             }
            if(temp==operations[6])//sqrt
               
              String s = text.getText();
              if (s.charAt(0) == '-')
               {
                 text.setText("负数不能开根号");
               }
              else
                 text.setText(Double.toString(java.lang.Math.sqrt(Double.parseDouble(text.getText()))));
              clear=false;
              }
             if(temp==operations[12])//  1/x
              {
               if(text.getText().charAt(0) == '0'&&text.getText().length() == 1)
                {
                 text.setText("除数不能为零");
                }
               else
                {
                 boolean isDec = true;
                 int i, j, k;
                 String s = Double.toString(1 / Double.parseDouble(text.getText()));
                 for (i = 0; i < s.length(); i++)
                 if (s.charAt(i) == '.')
                 break;
                 for (j = i + 1; j < s.length(); j++)
                 if (s.charAt(j) != '0')
                  {
                   isDec = false;
                   break;
                  }
                 if (isDec == true)
                  {
                   String stemp = "";
                   for (k = 0; k < i; k++)
                      stemp += s.charAt(k);
                    text.setText(stemp);
                   }
               else
                 text.setText(s);
                }
               clear=false;
               }
             if(temp==operations[11])// sin
              {
               text.setText(Double.toString(java.lang.Math.sin(Double.parseDouble(text.getText())*3.1415926/180.0)));
               clear=false;
              }
             if (temp ==operations[7]) //  +/-
              {
               boolean isNumber = true;
               String s = text.getText();
               for (int i = 0; i < s.length(); i++)
                if (! (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.' || s.charAt(i) == '-'))
                 {
                  isNumber = false;
                  break;
                 }
               if (isNumber == true)
                 { //如果当前字符串首字母有'-'号,代表现在是个负数,再按下时,则将首符号去掉
                  if (s.charAt(0) == '-')
                   {
                    text.setText("");
                    for (int i = 1; i < s.length(); i++)
                     {
                      char a = s.charAt(i);
                      text.setText(text.getText() + a);
                     }
                   }
                else //如果当前字符串第一个字符不是符号,则添加一个符号在首字母处
                   text.setText('-' + s);
                  }
                 }
              }//
            catch(Exception eee)
             {
              System.out.println("运算时,首先输入数字或字符");
              text.setText("运算出错");
              clear=false;
             }
           }

  class WindowDestroyer extends WindowAdapter
          {//退出窗口动作
           public void windowClosing(WindowEvent e)
            {
             System.exit(0);
            }
          }

        public static void main(String arg[])//产生窗口
         {
          Calculator calculator = new Calculator();
          calculator.setVisible(true);
         }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有