Java实现计算器----【完全自主完成】

来源:互联网 发布:java代码解压rar文件 编辑:程序博客网 时间:2024/06/05 11:16
Code:
  1. import java.awt.*;   
  2. import java.awt.event.*;   
  3. import javax.swing.*;   
  4. import javax.swing.border.BevelBorder;   
  5. import javax.swing.border.Border;   
  6. public class SwingCalculator implements ActionListener{   
  7.     public JButton makeButton(String label, Color color, Font font) {   
  8.         JButton b = new JButton(label);   
  9.         //b.setBackground(color);   
  10.         b.setFont(font);   
  11.         return b;   
  12.     }   
  13.     public JPanel makePanel(LayoutManager lm, Color c) {   
  14.         JPanel p = new JPanel();   
  15.         p.setLayout(lm);   
  16.         //p.setBackground(c);   
  17.         return p;   
  18.     }   
  19.     public void init() {//初始化GUI   
  20.         frame = new JFrame("MyCalculator");   
  21.         valueField = new JTextField(50);   
  22.         p1 = makePanel(new GridLayout(0,3,4,4),Color.lightGray);   
  23.         p2 = makePanel(new BorderLayout(6,2),Color.lightGray);   
  24.         p3 = makePanel(new BorderLayout(4,10),Color.lightGray);   
  25.         leftPanel = makePanel(new GridLayout(5,0,4,4),Color.lightGray);   
  26.            
  27.         border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);   
  28.         jlabel = new JLabel();//MC上方方框   
  29.         jlabel.setHorizontalAlignment(JLabel.CENTER);   
  30.         jlabel.setBorder(border);   
  31.   
  32.         mc = makeButton("MC",colorBlue,f);//MC   
  33.         mc.setForeground(Color.RED);   
  34.         mc.addActionListener(this);   
  35.         mr = makeButton("MR",colorBlue,f);//MR   
  36.         mr.addActionListener(this);   
  37.         mr.setForeground(Color.RED);   
  38.         ms = makeButton("MS",colorBlue,f);//MS   
  39.         ms.addActionListener(this);   
  40.         ms.setForeground(Color.RED);   
  41.         ma = makeButton("M+",colorBlue,f);//M+   
  42.         ma.setForeground(Color.RED);   
  43.         ma.addActionListener(this);   
  44.            
  45.         bs = makeButton("BackSpace",colorBlue,f);//BackSpace   
  46.         bs.addActionListener(this);   
  47.         ce = makeButton("CE",colorBlue,f);//CE   
  48.         ce.addActionListener(this);   
  49.         c = makeButton("C",colorBlue,f);//C   
  50.         c.addActionListener(this);   
  51.            
  52.         midPanel = makePanel(new GridLayout(4,5,4,2),Color.lightGray );   
  53.         midButtons = new JButton[20];   
  54.         midButtons[0] = makeButton("7",colorBlue,f);//7   
  55.         midButtons[1] = makeButton("8",colorBlue,f);//8   
  56.         midButtons[2] = makeButton("9",colorBlue,f);//9   
  57.         midButtons[3] = makeButton("/",colorBlue,f);// '/'   
  58.         midButtons[3].setForeground(Color.RED);   
  59.         midButtons[4] = makeButton("sqrt",colorBlue,f);//sqrt   
  60.            
  61.         midButtons[5] = makeButton("4",colorBlue,f);//4   
  62.         midButtons[6] = makeButton("5",colorBlue,f);//5   
  63.         midButtons[7] = makeButton("6",colorBlue,f);//6   
  64.         midButtons[8] = makeButton("*",colorBlue,f);//*   
  65.         midButtons[8].setForeground(Color.RED);   
  66.         midButtons[9] = makeButton("%",colorBlue,f);//%   
  67.            
  68.         midButtons[10] = makeButton("1",colorBlue,f);//1   
  69.         midButtons[11] = makeButton("2",colorBlue,f);//3   
  70.         midButtons[12] = makeButton("3",colorBlue,f);//3   
  71.         midButtons[13] = makeButton("-",colorBlue,f);// -   
  72.         midButtons[13].setForeground(Color.RED);   
  73.         midButtons[14] = makeButton("1/x",colorBlue,f);//1/x   
  74.            
  75.         midButtons[15] = makeButton("0",colorBlue,f);//0   
  76.         midButtons[16] = makeButton("+/-",colorBlue,f);// +/-   
  77.         midButtons[17] = makeButton(".",colorBlue,f);// .   
  78.         midButtons[18] = makeButton("+",colorBlue,f);// +   
  79.         midButtons[18].setForeground(Color.RED);   
  80.         midButtons[19] = makeButton("=",colorBlue,f);// =   
  81.         midButtons[19].setForeground(Color.RED);   
  82.            
  83.         midPanel.setForeground(Color.BLUE);   
  84.         for(int i = 0; i<20;i++) {   
  85.             midPanel.add(midButtons[i]);   
  86.             midButtons[i].addActionListener(this);   
  87.         }   
  88.         leftPanel.add(jlabel);   
  89.         leftPanel.add(mc);   
  90.         leftPanel.add(mr);   
  91.         leftPanel.add(ms);   
  92.         leftPanel.add(ma);   
  93.         p1.add(bs,"West");   
  94.         p1.add(ce,"Center");   
  95.         p1.add(c,"East");   
  96.         p2.add(p1,"North");   
  97.         p2.add(midPanel,"Center");   
  98.         p3.add(leftPanel,"West");   
  99.         p3.add(p2,"Center");   
  100.         frame.addWindowListener(new  WindowAdapter(){   
  101.             public void windowClosing(WindowEvent e){   
  102.                 System.exit(0);}});   
  103.         valueField.setHorizontalAlignment(JTextField.RIGHT);   
  104.         valueField.setFont(new Font("Courier",Font.PLAIN ,15));   
  105.         valueField.setText(value);   
  106.         valueField.setEditable(false);   
  107.         frame.add(valueField,"North");   
  108.         frame.add(p3,"Center");   
  109.         frame.setLocation(200,200);   
  110.         frame.setSize(380250);   
  111.         frame.setResizable(false);   
  112.         clearCalc();//初始化   
  113.         frame.setVisible(true);   
  114.     }          
  115.     public void actionPerformed(ActionEvent e) {   
  116.         String s = (String)e.getActionCommand();//获取事件源   
  117.         if(hasError&"CE".indexOf(s)==-1)//如果错误尾处理   
  118.             return;   
  119.         if(digits.indexOf(s) != -1)   
  120.             handleDigit(s);//数字"0123456789"   
  121.         else if(s.equals("."))//小数点   
  122.             handleDecimal();   
  123.         else if(normalOperators.indexOf(s) != -1)   
  124.             handleNormalOperator(s);//"+-*/="   
  125.         else if(mathOperators.indexOf(s) != -1)   
  126.             handleMathOperator(s);//"+/-sqrt%1/x"   
  127.         else if(editOperators.indexOf(s) != -1)   
  128.             handleEditOperator(s);//"CECBackSpace"   
  129.         else if(memoryOperators.indexOf(s) != -1)   
  130.             handleMemoryOperator(s);//"MRMCMSM+"   
  131.     }   
  132.     private void handleDigit(String s)   
  133.     {//"0123456789"   
  134.         if(newOpd) {//新的数字   
  135.             valueField.setText(s);   
  136.             newOpd = false;   
  137.         }else {   
  138.             String vs = valueField.getText();   
  139.             System.out.println(vs);   
  140.             //if(vs.trim().equals("0"))   
  141.                 valueField.setText(s);   
  142.             //else   
  143.             //valueField.setText(vs + s);   
  144.         }   
  145.         sawAnOpd = true;   
  146.     }   
  147.     private void clearCalc()   
  148.     {//清除数据   
  149.         sawDecimal =false;//小数点   
  150.         newOpd = true;//新数字   
  151.         sawAnOpd = false;//是否有操作数   
  152.         lastOptr = "";//操作码   
  153.         valueField.setText(value);   
  154.         hasError = false;//错误   
  155.     }   
  156.     private void handleNormalOperator(String s)   
  157.     {//"+-*/="   
  158.         if(!sawAnOpd)   
  159.             return;   
  160.         if(lastOptr.equals("+"))//+   
  161.             opd1 += getDisplay();   
  162.         else if(lastOptr.equals("-"))//-   
  163.             opd1 -= getDisplay();   
  164.         else if(lastOptr.equals("*"))//*   
  165.             opd1 *= getDisplay();   
  166.         else if(lastOptr.equals("/")){// '/'   
  167.             opd2 = getDisplay();   
  168.             if(opd2 == 0.0) {//除数为0   
  169.                 handleError();   
  170.                 return;   
  171.             }else  
  172.                 opd1 /=opd2;   
  173.         }   
  174.         else  
  175.             opd1 = getDisplay();//=   
  176.            
  177.         valueField.setText(opd1 + "");   
  178.         lastOptr = s;   
  179.         sawDecimal = false;   
  180.         newOpd = true;   
  181.     }   
  182.     private void handleError()   
  183.     {//处理错误   
  184.         System.out.println("Error");   
  185.         opd2 = getDisplay();   
  186.         hasError = true;   
  187.         valueField.setText("error");   
  188.     }   
  189.        
  190.     private void handleMathOperator(String s)   
  191.     {//"+/-sqrt % 1/x";   
  192.         if(!sawAnOpd)   
  193.             return;   
  194.         if(s.equals("sqrt")) {//sqrt   
  195.             if((opd2=getDisplay())>=0)   
  196.                 opd2 = Math.sqrt(opd2);   
  197.             else {//被开方数为负   
  198.                 handleError();   
  199.                 return;   
  200.             }   
  201.         }   
  202.         else if(s.equals("%"))//%   
  203.             opd2 = getDisplay()/100.0;   
  204.         else if(s.equals("1/x")){//1/x   
  205.             opd2 = getDisplay();   
  206.             if(opd2 == 0.0) {//操作数为0   
  207.                 handleError();   
  208.                 return;   
  209.             }   
  210.             else  
  211.                 opd2 = 1/opd2;   
  212.         }   
  213.         else if(s.equals("+/-"))   
  214.             opd2 = -getDisplay();//操作数取反   
  215.            
  216.         valueField.setText(opd2 + "");   
  217.         if(valueField.getText().indexOf(".")!=-1)   
  218.             sawDecimal = false;   
  219.         else  
  220.             sawDecimal = true;   
  221.            
  222.         newOpd = false;   
  223.     }   
  224.     private void handleEditOperator(String s)   
  225.     {//"CECBackSpace";   
  226.         if(!sawAnOpd)   
  227.             return;   
  228.         if(s.equals("CE")) {//CE   
  229.             if(hasError) {   
  230.                 hasError = false;   
  231.                 valueField.setText(opd2 + "");   
  232.             }   
  233.         }   
  234.         else if(s.equals("BackSpace"))   
  235.             {//BackSpace   
  236.                 String vs = valueField.getText();   
  237.                 if(!newOpd)   
  238.                     if((opd2 = getDisplay())!=0.0) {   
  239.                         vs=vs.substring(0,vs.length()-1);   
  240.                         if(vs.equals("")) {//已经清除完   
  241.                             vs="0";   
  242.                             newOpd = true;   
  243.                         }   
  244.                         valueField.setText(vs);    
  245.                         if(vs.indexOf(".")!=-1)   
  246.                             sawDecimal = false;   
  247.                         else  
  248.                             sawDecimal = true;   
  249.                         return;   
  250.                     }   
  251.             }    
  252.         else if(s.equals("C")) {//C   
  253.             clearCalc();   
  254.         }   
  255.     }   
  256.     private void handleMemoryOperator(String s)   
  257.     {//"MCMRMSM+";   
  258.         if(s.equals("MS")) {//MS   
  259.             storedMomery = getDisplay();   
  260.             jlabel.setText("M");   
  261.         }   
  262.         else if(s.equals("MR")) {//MR   
  263.             valueField.setText(storedMomery + "");   
  264.             newOpd = false;   
  265.             }   
  266.         else if(s.equals("MC")) {//MC   
  267.             storedMomery = 0.0;   
  268.             jlabel.setText("");   
  269.         }   
  270.         else if(s.equals("M+")) {//M+   
  271.                 if(!newOpd)   
  272.                     storedMomery += getDisplay();   
  273.                 else storedMomery *= 2.0;   
  274.             }   
  275.     }          
  276.     private void handleDecimal()   
  277.     {//处理小数点   
  278.         if(!sawDecimal) {//还没有出现小数点   
  279.             if(newOpd) {   
  280.                 valueField.setText("0.");   
  281.                 newOpd = false;   
  282.             }else {   
  283.                 valueField.setText(valueField.getText() + ".");   
  284.             }   
  285.             sawDecimal = true;   
  286.         }   
  287.     }   
  288.     private double getDisplay()   
  289.     {//取当前显示数据   
  290.         return Double.parseDouble(valueField.getText());   
  291.     }   
  292.     public static void main(String[] args) {   
  293.         new SwingCalculator().init();   
  294.     }   
  295.     private JFrame frame;   
  296.     private String value="0";   
  297.     private JTextField valueField;   
  298.     private Border border;   
  299.     private JLabel jlabel;   
  300.     private JPanel leftPanel;   
  301.     private JPanel midPanel;   
  302.     private JPanel p1;   
  303.     private JPanel p2;   
  304.     private JPanel p3;   
  305.     private JButton[] midButtons;   
  306.     private Color colorBlue = Color.LIGHT_GRAY;   
  307.     private Font f = new Font("Courier",Font.PLAIN ,12);   
  308.     private JButton mc,mr,ms,ma;   
  309.     private JButton bs,ce,c;   
  310.     static final String digits = "0123456789";   
  311.     static final String normalOperators = "+-*/=";   
  312.     static final String mathOperators = "+/-sqrt%1/x";   
  313.     static final String editOperators = "CECBackSpace";   
  314.     static final String memoryOperators = "MRMCMSM+";   
  315.     private String lastOptr;   
  316.     private double opd1,opd2;   
  317.     private double storedMomery = 0.0;   
  318.     private boolean sawDecimal,newOpd,sawAnOpd,hasError;                       
  319. }   

 

原创粉丝点击