Java 计算器

Code:
  1. package graphics;  
  2. // debuged already ok  
  3. import java.util.Date;  
  4. import java.awt.*;  
  5. import java.awt.event.*;  
  6. import java.text.DecimalFormat;  
  7. import java.text.SimpleDateFormat;  
  8. //++  
  9. import java.io.BufferedReader;  
  10. import java.io.File;  
  11. import java.io.FileNotFoundException;  
  12. import java.io.FileReader;  
  13. import java.io.FileWriter;  
  14. import java.io.IOException;  
  15. //++  
  16. import javax.swing.*;  
  17. //import javax.swing.event.CaretEvent;  
  18. //import javax.swing.event.CaretListener;  
  19.   
  20. public class CalculatorX extends JFrame implements ActionListener  
  21. {  
  22.     /** 
  23.      *  
  24.      */  
  25.     public File file; //++  
  26.     private static final long serialVersionUID = 1L;  
  27.     private JButton but[],enter;  
  28.     public enum MyOperator{ADD, SUB, MUL, DIV}  
  29.     private MyOperator oper;  
  30.     private JTextField text_area;  
  31.     private double result, last;  
  32.     private HelpDialog viewdialog, helpdialog;  
  33.     private ClearDialog historydialog;  
  34.     ///private String historytext;  
  35.     private int flag, operatorflag, numberflag, enterflag;  
  36.     public CalculatorX() throws IOException  
  37.     {  
  38.         super("CalculatorX");  
  39.         this.setResizable(false);  
  40.         this.setAlwaysOnTop(true);  
  41.         this.setBounds(300245240340);  
  42.         this.setDefaultCloseOperation(3);  
  43.           
  44.         this.file = new File("cacu_history");  
  45.         if(this.file.length() != 0)  
  46.             this.writeToFile("/n----------------------" + //怎么才能放在析构函数里  
  47.                              "--------------------/n/n");                                  
  48.           
  49.         text_area = new JTextField("0");  
  50.         text_area.setEditable(false);  
  51.           
  52.           
  53.         Dimension mini_size  = new Dimension(1000,40);  
  54.         text_area.setPreferredSize(mini_size);  
  55.         System.out.println("tr"+text_area.getSize().width+"tr"+text_area.getHeight());  
  56.            
  57.         text_area.setFont(new Font("Consolas"025));//"Default", Font.bold, 20  
  58.         text_area.setHorizontalAlignment(JTextField.RIGHT);  
  59.         this.getContentPane().add(text_area, BorderLayout.NORTH);  
  60.               
  61.           
  62.   
  63.         JPanel jpanel = new JPanel();  
  64.         jpanel.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));  
  65.         this.getContentPane().add(jpanel);             //  
  66.           
  67.         JPanel jpanel_max = new JPanel();  
  68.         Dimension jpmax_size  = new Dimension(225,141);  
  69.         jpanel_max.setPreferredSize(jpmax_size);  
  70.         jpanel_max.setLayout(new FlowLayout(FlowLayout.RIGHT,5,7));  
  71.         jpanel.add(jpanel_max);  
  72.           
  73.   
  74.         JPanel jpanel_min = new JPanel();  
  75.         Dimension jpmin_size  = new Dimension(170,100);  
  76.         jpanel_min.setPreferredSize(jpmin_size);  
  77.         jpanel_min.setLayout(new FlowLayout(FlowLayout.RIGHT,5,7));  
  78.         jpanel.add(jpanel_min);  
  79.           
  80.         JPanel jpanel_enter = new JPanel(new FlowLayout(FlowLayout.RIGHT,5,7));   
  81.         Dimension enter_panel_size  = new Dimension(55,100);  
  82.         jpanel_enter.setPreferredSize(enter_panel_size);  
  83.         jpanel.add(jpanel_enter);  
  84.           
  85.         String b[] = {"√""±""C""+""7""8""9""-""4""5""6",  
  86.                    //  0     1     2    3    4    5    6    7    8    9    10     
  87.                 "*""1""2""3""0"".""/"};   
  88.                //11   12  13   14    15   16   17  
  89.         but = new JButton[b.length];  
  90.           
  91.         for(int i = 0; i<12; i++)  
  92.         {  
  93.             but[i] = new JButton(b[i]);   
  94.             Dimension same_size  = new Dimension(50,40);  
  95.             but[i].setPreferredSize(same_size);  
  96.             if(i > 0)  
  97.                 but[i].setFont(new Font("Default"016));  
  98.             but[i].addActionListener(this);  
  99.             jpanel_max.add(but[i]);  
  100.         }  
  101.           
  102.         for(int i = 12; i<18; i++)  
  103.         {  
  104.             but[i] = new JButton(b[i]);   
  105.             Dimension same_size  = new Dimension(50,40);  
  106.             but[i].setPreferredSize(same_size);  
  107.             but[i].setFont(new Font("Default"016));  
  108.             but[i].addActionListener(this);  
  109.             jpanel_min.add(but[i]);  
  110.         }  
  111.           
  112.         enter = new JButton("=");  
  113.         enter.setFont(new Font("Consolas"025));  
  114.         Dimension same_size = new Dimension(50,86);  
  115.         enter.setPreferredSize(same_size);  
  116.         enter.addActionListener(this);  
  117.         jpanel_enter.add(enter);  
  118.           
  119.         addmiiMenu();  
  120.           
  121.         this.setVisible(true);  
  122.   
  123.         helpdialog = new HelpDialog(this"关于产品"320150);  
  124.         viewdialog = new HelpDialog(this"使用说明"420350);  
  125.         historydialog = new ClearDialog(this"计算记录"620400);  
  126.     }  
  127.     public void finalize() throws IOException//没有用     待解决  
  128.     {  
  129.         System.out.print("  finalize() throws IOException ");//NOY  
  130.         this.writeToFile("---------------------------" +  
  131.                 "/n");     
  132.     }  
  133.     public void addmiiMenu()  
  134.     {  
  135.         JMenuBar menubar = new JMenuBar();  
  136.         this.setJMenuBar(menubar);  
  137.           
  138.         String menustr[] = {"查看""文件""帮助(F1)"};   
  139.         JMenu menu[] = new JMenu[menustr.length];  
  140.         for(int i = 0; i<menustr.length; i++)  
  141.         {  
  142.             menu[i] = new JMenu(menustr[i]);  
  143.             menubar.add(menu[i]);  
  144.         }  
  145.         JMenuItem menu_view_history = new JMenuItem("查看计算记录");  
  146.         menu_view_history.addActionListener(this);  
  147.         menu[0].add(menu_view_history);  
  148.   
  149.         JMenuItem menu_help_view = new JMenuItem("查看帮助  ");  
  150.         menu_help_view.addActionListener(this);  
  151.           
  152.         menu_help_view.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, InputEvent.CTRL_MASK));  
  153.         JMenuItem menu_help_about = new JMenuItem("关于计算器");  
  154.         menu_help_about.addActionListener(this);  
  155.         menu[2].add(menu_help_view);  
  156.         menu[2].addSeparator();   
  157.         menu[2].add(menu_help_about);  
  158.         menu[2].setMnemonic(KeyEvent.VK_F1);  
  159.           
  160.     }  
  161.     public static void main(String args[]) throws IOException  
  162.     {  
  163.         new CalculatorX();  
  164.     }  
  165.     private class ClearDialog extends JDialog implements ActionListener  
  166.     {  
  167.         /** 
  168.          *  
  169.          */  
  170.         private static final long serialVersionUID = 1L;  
  171.         JFrame jframe;  
  172.         JPanel jpanel;  
  173.         JTextArea jtexr;  
  174.         public JButton clear;  
  175.         ClearDialog(JFrame jframe, String st, int wid, int hig)  
  176.         {  
  177.             super(jframe, st, true);  
  178.             this.jframe=jframe;                //  
  179.             this.setSize(wid,hig);  
  180.             jpanel = new JPanel();  
  181.             clear = new JButton("删除记录");  
  182.             clear.addActionListener(this);  
  183.             clear.addActionListener((ActionListener) jframe);  
  184.             //this.getContentPane().setLayout(new FlowLayout());  
  185.             this.getContentPane().add(jpanel, "North");  
  186.             jpanel.setLayout(new FlowLayout(FlowLayout.LEFT));  
  187.             jpanel.add(clear);  
  188.               
  189.             jtexr = new JTextArea("");  
  190.             jtexr.setEditable(true);  
  191.             jtexr.setFont(new Font("仿宋"115));  
  192.             jtexr.setLineWrap(true);                        //自动换行  
  193.               
  194.             this.getContentPane().add(new JScrollPane(jtexr));  
  195.             this.setDefaultCloseOperation(HIDE_ON_CLOSE);             
  196.         }  
  197.         void show (String message)  
  198.         {  
  199.             jtexr.setText(message);  
  200.             this.setLocation(jframe.getX()+100,jframe.getY()+100);  
  201.             this.setVisible(true);  
  202.         }  
  203.         @Override  
  204.         public void actionPerformed(ActionEvent e) {  
  205.             // TODO Auto-generated method stub  
  206.             if(e.getSource()instanceof JButton)  
  207.             {     
  208.                 jtexr.setText("");  
  209.             }  
  210.         }  
  211.     }  
  212.     private class HelpDialog extends JDialog  
  213.     {  
  214.         /** 
  215.          *  
  216.          */  
  217.         private static final long serialVersionUID = 1L;  
  218.         JFrame jframe;  
  219.         JTextArea jtexr;  
  220.         HelpDialog(JFrame jframe, String st, int wid, int hig)  
  221.         {  
  222.             super(jframe, st, true);  
  223.             this.jframe=jframe;                //  
  224.             this.setSize(wid,hig);  
  225.       
  226.             jtexr = new JTextArea("");  
  227.             jtexr.setEditable(false);  
  228.             jtexr.setFont(new Font("仿宋"115));  
  229.             jtexr.setLineWrap(true);                        //自动换行  
  230.             //jtexr.setEnabled(false);  
  231.             this.getContentPane().add(new JScrollPane(jtexr));  
  232.             this.setDefaultCloseOperation(HIDE_ON_CLOSE);             
  233.         }  
  234.         void show (String message)  
  235.         {  
  236.             jtexr.setText(message);  
  237.             this.setLocation(jframe.getX()+100,jframe.getY()+100);  
  238.             this.setVisible(true);  
  239.         }  
  240.     }  
  241.     @Override  
  242.       
  243.     public void actionPerformed(ActionEvent e)   
  244.     {  
  245.         // TODO Auto-generated method stub  
  246.         if(e.getSource() == historydialog.clear)   
  247.         {  
  248.             this.file.delete();  
  249.             this.file = new File("cacu_history");  
  250.         }  
  251.               
  252.           
  253.           
  254.         DecimalFormat df = new DecimalFormat("#############.#############");  
  255.         if(e.getSource()instanceof JMenuItem)                    //MenuItem  
  256.         {  
  257.             if(e.getActionCommand()==("查看计算记录"))  
  258.                 try {  
  259.                     if(this.file.length()!=0)  
  260.                         historydialog.show(this.readFromFile());  
  261.                     else  
  262.                         historydialog.show("无记录");  
  263.                 } catch (IOException e1) {  
  264.                     // TODO Auto-generated catch block  
  265.                     e1.printStackTrace();  
  266.                 }  
  267.   
  268.               
  269.             if(e.getActionCommand()=="查看帮助  ")  
  270.                 viewdialog.show("实验中" +  
  271.                         "已经将确认键立起" +  
  272.                         "/n/n" +  
  273.                         "解决了小数点移位,使之趋于精确" +  
  274.                         "/n/n" +  
  275.                         "解决了无优先级连徐运算  最大长度仍可输入并运算" +  
  276.                         "/n/n" +  
  277.                         "可以使用计算器进行如加、减、乘、除这样简单的运算。" +  
  278.                         "/n/n" +  
  279.                         "单击“查看”菜单,然后单击所需模式。" +  
  280.                         "/n/n" +  
  281.                         "切换模式时,将清除当前的计算。但会保留“记忆钥匙”所存储的计算历史记录和数字。" +  
  282.                         "/n/n" +  
  283.                         "单击计算器键进行所需的计算");  
  284.             if(e.getActionCommand()=="关于计算器")  
  285.                 helpdialog.show("/n/n    All rights reserved by " +  
  286.                         "/n       Mr Baoning Gai" +  
  287.                         "/n         11/16/2010");         
  288.         }  
  289.         if(e.getSource()instanceof JButton)  
  290.         {  
  291.             if( text_area.getText().equals("Overflow")||text_area.getText().equals("Error : Infinity")||text_area.getText().equals("Error :NaN") )  
  292.                 Clear();  
  293.             if( (text_area.getText().length()-flag)<15||operatorflag==1 )  
  294.             {  
  295.                 if(e.getSource()==but[4])  
  296.                 {  
  297.                     Addnumber(7);  
  298.                 }  
  299.                 if(e.getSource()==but[5])  
  300.                 {     
  301.                     Addnumber(8);  
  302.                 }  
  303.                 if(e.getSource()==but[6])  
  304.                 {     
  305.                     Addnumber(9);  
  306.                 }  
  307.                 if(e.getSource()==but[8])  
  308.                 {     
  309.                     Addnumber(4);  
  310.                 }  
  311.                 if(e.getSource()==but[9])  
  312.                 {     
  313.                     Addnumber(5);  
  314.                 }  
  315.                 if(e.getSource()==but[10])  
  316.                 {     
  317.                     Addnumber(6);  
  318.                 }  
  319.                 if(e.getSource()==but[12])  
  320.                 {     
  321.                     Addnumber(1);  
  322.                 }  
  323.                 if(e.getSource()==but[13])  
  324.                 {     
  325.                     Addnumber(2);  
  326.                 }  
  327.                 if(e.getSource()==but[14])  
  328.                 {     
  329.                     Addnumber(3);  
  330.                 }  
  331.                 if(e.getSource()==but[15])  
  332.                 {     
  333.                     Addnumber(0);  
  334.                 }  
  335.             }  
  336.               
  337.               
  338.                 if(e.getSource()==but[16])                     //not complement  
  339.                 {  
  340.                     try  
  341.                     {  
  342.                         Integer.parseInt(text_area.getText());  
  343.                         flag = 1;  
  344.                     }  
  345.                     catch(NumberFormatException nfe)  
  346.                     {  
  347.                         System.out.println("!");  
  348.                     }  
  349.                     finally{}     
  350.                  }  
  351.                 if(e.getSource()==but[3])                     //not complement  
  352.                 {  
  353.                       
  354.                     if(numberflag == 1&&oper != null)  
  355.                         try {  
  356.                             Operate();  
  357.                         } catch (IOException e1) {  
  358.                             // TODO Auto-generated catch block  
  359.                             e1.printStackTrace();  
  360.                         }  
  361.                     result = Double.parseDouble( text_area.getText() );  
  362.                     oper = MyOperator.ADD;  
  363.                     operatorflag = 1;  
  364.                     numberflag = 0;  
  365.                     enterflag = 0;//  
  366.                 }  
  367.                 if(e.getSource()==but[7])                     //not complement  
  368.                 {  
  369.                     if(numberflag == 1&&oper != null)  
  370.                         try {  
  371.                             Operate();  
  372.                         } catch (IOException e1) {  
  373.                             // TODO Auto-generated catch block  
  374.                             e1.printStackTrace();  
  375.                         }  
  376.                     result = Double.parseDouble( text_area.getText() );  
  377.                     oper = MyOperator.SUB;  
  378.                     operatorflag = 1;  
  379.                     numberflag = 0;  
  380.                     enterflag = 0;//  
  381.                 }  
  382.                 if(e.getSource()==but[11])                     //not complement  
  383.                 {  
  384.                     if(numberflag == 1&&oper != null)  
  385.                         try {  
  386.                             Operate();  
  387.                         } catch (IOException e1) {  
  388.                             // TODO Auto-generated catch block  
  389.                             e1.printStackTrace();  
  390.                         }  
  391.                     result = Double.parseDouble( text_area.getText() );  
  392.                     oper = MyOperator.MUL;  
  393.                     operatorflag = 1;  
  394.                     numberflag = 0;  
  395.                     enterflag = 0;//  
  396.                 }  
  397.                 if(e.getSource()==but[17])                     //not complement  
  398.                 {  
  399.                     if(numberflag == 1&&oper != null)  
  400.                         try {  
  401.                             Operate();  
  402.                         } catch (IOException e1) {  
  403.                             // TODO Auto-generated catch block  
  404.                             e1.printStackTrace();  
  405.                         }  
  406.                     result = Double.parseDouble( text_area.getText() );  
  407.                     oper = MyOperator.DIV;  
  408.                     operatorflag = 1;  
  409.                     numberflag = 0;  
  410.                     enterflag = 0;//  = 之后可以用当前数做前值  
  411.                 }  
  412.                 if(e.getSource()==but[0])                     //求根  
  413.                 {  
  414.                     double a = Double.parseDouble( text_area.getText() );  
  415.                     if(a<=0)  
  416.                     {  
  417.                         text_area.setText("Error :NaN");  
  418.                         return;  
  419.                     }  
  420.                     a = Math.sqrt(a);  
  421.                     String str = "" + df.format(a);  
  422.                     try {  
  423.                         this.writeToFile("sqrt(" + text_area.getText() + ") =" + a + Addtime() + "/n");  
  424.                         }   
  425.                     catch (IOException e1) {}  
  426.                     text_area.setText(str);  
  427.                     result = Double.parseDouble( text_area.getText() );  
  428.                     operatorflag = 1;  
  429.                   
  430.                 }  
  431.                 if(e.getSource()==but[1])                     //not complement  
  432.                 {  
  433.                     double a = Double.parseDouble( text_area.getText() );  
  434.                     a = 0 - a;  
  435.                     String str = "" + df.format(a);  
  436.                     text_area.setText(str);  
  437.                     result = Double.parseDouble( text_area.getText() );  
  438.                 }  
  439.                 if(e.getSource()==but[2])                     //not complement  
  440.                 {  
  441.                 Clear();   
  442.                 }  
  443.                 if(e.getSource()==enter&&oper!=null)                     // complement  
  444.                     {  
  445.                     try {  
  446.                         Operate();  
  447.                     } catch (IOException e1) {  
  448.                         // TODO Auto-generated catch block  
  449.                         e1.printStackTrace();  
  450.                     }  
  451.                     operatorflag = 1;      //仅仅是为了变 0   
  452.                     enterflag = 1;  
  453.                 }         
  454.             System.out.print(" result="+result);//NOY  
  455.             System.out.print(" last="+last);//NOY  
  456.             System.out.print(" flag="+flag);//NOY  
  457.             System.out.print(" operatorflag="+operatorflag);//NOYoperatorflag  
  458.             System.out.print(" numberflag="+numberflag);  
  459.             System.out.print(oper);         //NOY  
  460.             System.out.println("!!!!!!!  enterflag="+enterflag);  
  461.         }  
  462.     }  
  463.     public void Clear()  
  464.     {  
  465.         text_area.setText("0");  
  466.         oper = null;  
  467.         result = 0;  
  468.         operatorflag = 0;  
  469.         numberflag = 0;  
  470.     }  
  471.     public String Pointmove(String str, int len)        //小数点移位  
  472.     {  
  473.         int point_position = str.indexOf(".")+1;   //查找小数点的位置  
  474.         int point_number = str.length() - point_position;  
  475.         int delete_number = str.length() - len;    //与小数点无关  
  476.         int need_number = point_number - delete_number;  
  477.           
  478.         String str_format = "#";  
  479.         if(need_number<0||point_position>15)  
  480.             return "Overflow";  
  481.         if(need_number>0)  
  482.             str_format += ".";  
  483.           
  484.         for(int i=0; i<need_number; i++)  
  485.         {  
  486.             str_format+="#";  
  487.         }  
  488.         DecimalFormat df = new DecimalFormat(str_format);  
  489.         String st = "" + df.format(Double.parseDouble(str));  
  490.         if(st.length()>15)  
  491.             return "Overflow";                //因为小数点位置在大于15 或无小数点时仍应控制长度  
  492.         return st;  
  493.     }  
  494.     public String Addtime()  
  495.     {  
  496.         SimpleDateFormat format_time = new SimpleDateFormat("HH:mm ss,MM/dd/yyyy");  
  497.         Date currenttime = new Date();  
  498.         String str_time = " time:" + format_time.format(currenttime);  
  499.         return str_time;  
  500.     }  
  501.     public void Addnumber(int getnumber)  
  502.     {  
  503.         DecimalFormat df = new DecimalFormat("#############.#############");  
  504.         String str;  
  505.         if(enterflag==1)  
  506.             oper = null;  
  507.         if(operatorflag==1)  
  508.         {  
  509.             str = "0";  
  510.             operatorflag = 0;  
  511.         }  
  512.         else  
  513.         {  
  514.             str = text_area.getText();  
  515.         }  
  516.         if(flag==1)  
  517.         {  
  518.             str += ".";  
  519.             flag = 0;  
  520.         }  
  521.             numberflag = 1;  
  522.             enterflag = 0;  
  523.             str =str+getnumber;  
  524.         double input = Double.parseDouble( str );  
  525.         str = "" + df.format(input);  
  526.         last = input;  
  527.         text_area.setText(str);  
  528.         System.out.println("click "+getnumber);  
  529.     }  
  530.     public void Operate() throws IOException  
  531.     {  
  532.         DecimalFormat df = new DecimalFormat("#############.#############");  
  533.         System.out.println("clik enter");               //NOY  
  534.           double b = last;  
  535.           double a = result;  
  536.           String add_history = "";  
  537.             switch(oper)  
  538.             {  
  539.             case ADD :  
  540.                 add_history =a+"+"+b+"="+(a+b)+Addtime()+"/n";   
  541.                 a = a+b;  
  542.                 break;  
  543.             case SUB :  
  544.                 add_history =a+"-"+b+"="+(a+b)+Addtime()+"/n";  
  545.                 a = a-b;       
  546.                 break;  
  547.             case MUL :  
  548.                 add_history =a+"*"+b+"="+(a+b)+Addtime()+"/n";   
  549.                 a = a*b;   
  550.                 break;  
  551.             case DIV :  
  552.                 a = a/b;  
  553.                 add_history =a+"/"+b+"="+(a+b)+Addtime()+"/n";   
  554.                 if(b==0)  
  555.                 {  
  556.                     text_area.setText("Error : Infinity");  
  557.                     return;  
  558.                 }     
  559.                 break;        
  560.             }  
  561.             numberflag = 0;  
  562.             result = a;  
  563.             String str = "" + df.format(result);  
  564.             //++  
  565.             this.writeToFile(add_history);  
  566.             //++  
  567.             if(str.length()<=15)  
  568.             {         
  569.                 text_area.setText(str);  
  570.             }  
  571.             else  
  572.             {  
  573.                 str = Pointmove(str, 15);  
  574.                 text_area.setText(str);  
  575.             }  
  576.     }  
  577.     public void writeToFile( String lines ) throws IOException//将字符串lines写入当前文本文件中  
  578.     {  
  579.           
  580.             FileWriter fout = new FileWriter(this.file, true);//文件字符流对象
  581.             fout.write(lines);                 //向文件字符流写入一个字符串  
  582.             fout.close();  
  583.     }  
  584.     public String readFromFile() throws IOException//使用流从当前文本文件中读取字符  
  585.     {  
  586.         System.out.println("read");  
  587.         char lines[] = null;  
  588.             FileReader fin = new FileReader( this.file );//创建字符输入流对象  
  589.             lines = new char[(int)this.file.length()];  
  590.             fin.read(lines);                             //读取字符流到字符数组  
  591.             fin.close();  
  592.             return new String(lines);  
  593.     }  
  594. }  

 

你可能感兴趣的:(Java 计算器)