首页 > 代码库 > 使用Java实现的简单的计算器

使用Java实现的简单的计算器

package calculate;/** * @author Wayne; * @time 2014年7月14日; * @project java计算器2.0; */import java.awt.*;import java.awt.event.*;import java.text.DecimalFormat;import javax.swing.*;import javax.swing.JOptionPane;import javax.script.*;public class Calcul extends JFrame implements ActionListener,KeyListener{    private static final long serialVersionUID = 6256855493544342895L;        //一些全局初始化    JPanel buttonPanel = new JPanel(new GridLayout(5,4,3,3));//定义5*4网格,横向竖向间距为3px    JTextField dataspace = new JTextField("");//显示输入的文本    JTextField message = new  JTextField("就绪");//标题用户显示提示信息    String str[] = {"清除(C)","←","(",")","7","8","9","÷","4","5","6","×","1","2","3","-",".","0","等于(R)","+"};//按钮文字    private JButton btn[] = new JButton[str.length];//新建按钮        //字体和颜色    Font font = new Font("微软雅黑",Font.BOLD,22);//字体初始化    Color wordcolor = new Color(255,255,255);//字体设置为白色    Color textboxcolor = new Color(124,97,76);//消息框颜色为灰色    Color textboxcolor1 = new Color(125,125,125);//文本框颜色为灰色        public Calcul()    {        //一些初始化        setTitle("计算器");        setSize(WIDTH,HEIGHT);        setResizable(false);        setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));        //增加按钮并设置监听颜色等        for(int i = 0;i<str.length;i++)        {            btn[i] = new JButton(str[i]);            btn[i].setFont(font);            btn[i].addActionListener(this);            btn[i].addKeyListener(this);          // if((i>3 && i<7 ) || (i>7 && i<11) || ( i>11 && i<15) || i == 17)                btn[i].setBackground(new Color(104,152,104));           //else            //   btn[i].setBackground(new Color(99,154,157));            btn[i].setForeground(wordcolor);            buttonPanel.add(btn[i]);          }        btn[0].setBackground(new Color(204,88,56));        btn[7].setBackground(new Color(67,160,193));        btn[11].setBackground(new Color(67,160,193));        btn[15].setBackground(new Color(67,160,193));        btn[19].setBackground(new Color(67,160,193));          message.addKeyListener(this);                                //增加文本面板        JPanel textPanel = new JPanel(new GridLayout(2,1));                //将文本框加入到文本面板中                //提示框        message.setFont(font);        message.setPreferredSize(new Dimension(30,50));        message.setBackground(textboxcolor);        message.setForeground(wordcolor);        message.setEditable(false);        textPanel.add(message);                //缓冲区        dataspace.setFont(font);        dataspace.setPreferredSize(new Dimension(30,60));        dataspace.setBackground(textboxcolor1);        dataspace.setForeground(wordcolor);        dataspace.setEditable(false);        textPanel.add(dataspace);                //将组件加入到容器中        Container contentPane = getContentPane();        contentPane.add(buttonPanel,BorderLayout.CENTER);        contentPane.add(textPanel,BorderLayout.NORTH);            }    public static final int WIDTH = 500;    public static final int HEIGHT = 500;        public static void main(String[] args)    {        Calcul frame = new Calcul();        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();        frame.setLocation((dim.width - 350)/2,(dim.height - 500)/2);        frame.setVisible(true);    }    //判断输入是否为+-*/.的函数    public boolean NotSymbol(String str)    {        char strc = str.charAt(0);        if(strc == ‘*‘ || strc == ‘/‘ || strc == ‘+‘ || strc == ‘-‘ || strc == ‘.‘)        {            return false;        }        else         {                return true;        }    }    //判断前一个是否为+-*/.的函数    public boolean PreNotSym(String str)    {        String pre = str.substring(str.length()-1, str.length());        if(NotSymbol(pre))            return true;        else             return false;    }    //追加函数    public String addnum(String add)    {        String addbefore=dataspace.getText().trim();        String addafter = null;        message.setText("输入的为:");                if(addbefore.length() == 0 )        {            if(NotSymbol(add))                addafter=addbefore+add;            else if( !NotSymbol(add))                addafter = addbefore;        }                else if(addbefore.length() >= 2 )        {            if(PreNotSym(addbefore))            {                addafter=addbefore+add;            }            else             {                if(NotSymbol(add))                    addafter = addbefore + add;                else if( !NotSymbol(add))                    addafter = addbefore;            }                    }        else if(addbefore.length() == 1)        {            addafter = addbefore + add;        }        return addafter;    }    @Override    public void actionPerformed(ActionEvent e)    {        //清空        if (e.getSource() == btn[0] )        {            message.setText("就绪");            dataspace.setText("");        }                //退格        else if (e.getSource() == btn[1])        {            message.setText("就绪");            String data = dataspace.getText().trim();            if(data.length()>0)            {            if(data.charAt(0) != ‘-‘)            {                if(data.length() >1)                {                    if(data.charAt(data.length() - 2) == ‘.‘)                    {                        data = data.substring(0,data.length() -1);                        dataspace.setText(data);                    }                    data = data.substring(0,data.length() - 1);                    dataspace.setText(data);                }                    else if(data.length() == 1)                {                    dataspace.setText("");                }            }            else if(data.charAt(0) == ‘-‘)            {                if(data.length() >2)                {                    if(data.charAt(data.length() - 2) == ‘.‘)                    {                        data = data.substring(0,data.length() -1);                        dataspace.setText(data);                    }                    data = data.substring(0,data.length() - 1);                    dataspace.setText(data);                }                    else if(data.length() == 2)                {                    dataspace.setText("0");                }            }            else if(data =http://www.mamicode.com/="0")            {                dataspace.setText("");            }            }            else            {}        }                //左括号        else if(e.getSource() == btn[2])        {            String key = "(";            dataspace.setText(addnum(key));        }                //右括号        else if(e.getSource() == btn[3])        {            String key = ")";            dataspace.setText(addnum(key));        }                        //等号        else if(e.getSource() == btn[18])        {            message.setText("计算得到的结果为:");            ScriptEngineManager sem = new ScriptEngineManager();                    ScriptEngine se = sem.getEngineByName("js");            try            {                    int leng = dataspace.getText().length();                if(leng==0)                {                    message.setText("你好像没输入数据哦~!");                                                        }                else                {                                DecimalFormat df = new DecimalFormat("#.##"); //设置数据格式                     Object  result = se.eval(dataspace.getText());                    double value =http://www.mamicode.com/ Double.parseDouble(df.format(result));                     String valuestr = String.valueOf(value);                    dataspace.setText(valuestr);                }            }            catch (ScriptException evt)            {                message.setText("表达式似乎有错呢!请重新编辑");                }                    catch(NumberFormatException evt)            {                message.setText("除数不能为0哦,请重新编辑");            }        }                //加点        else if(e.getSource() == btn[16])        {            String key = ".";            dataspace.setText(addnum(key));        }                //加号        else if(e.getSource() == btn[19])        {            String key = "+";            dataspace.setText(addnum(key));        }                //减号        else if(e.getSource() == btn[15])        {            String key = "-";            dataspace.setText(addnum(key));        }                //乘号        else if(e.getSource() == btn[11])        {            String key = "*";            dataspace.setText(addnum(key));        }                                        //除号        else if(e.getSource() == btn[7])        {            String key = "/";            dataspace.setText(addnum(key));        }                //数字7        else if(e.getSource() == btn[4])        {            String key = "7";            dataspace.setText(addnum(key));        }                        //数字8        else if(e.getSource() == btn[5])        {            String key = "8";            dataspace.setText(addnum(key));        }                        //数字9        else if(e.getSource() == btn[6])        {            String key = "9";            dataspace.setText(addnum(key));        }                                //数字4        else if(e.getSource() == btn[8])        {            String key = "4";            dataspace.setText(addnum(key));        }                        //数字5        else if(e.getSource() == btn[9])        {            String key = "5";            dataspace.setText(addnum(key));        }                        //数字6        else if(e.getSource() == btn[10])        {            String key = "6";            dataspace.setText(addnum(key));        }                        //数字1        else if(e.getSource() == btn[12])        {            String key = "1";            dataspace.setText(addnum(key));        }                        //数字2        else if(e.getSource() == btn[13])        {            String key = "2";            dataspace.setText(addnum(key));        }                        //数字3        else if(e.getSource() == btn[14])        {            String key = "3";            dataspace.setText(addnum(key));        }                        //数字0        else if(e.getSource() == btn[17])        {            String key = "0";            dataspace.setText(addnum(key));                    }    }    @Override    public void keyTyped(KeyEvent e) {        // TODO 自动生成的方法存根            }    @Override    //按下按钮    public void keyReleased(KeyEvent e)     {        int keycode = e.getKeyCode();        //退出        if(keycode == 81)        {            int i = JOptionPane.showConfirmDialog(null, "是否退出?","提示:", JOptionPane.YES_NO_OPTION);            if(i == JOptionPane.OK_OPTION)             {                 System.exit(0);             }             else{ }        }        //清空        if (keycode == 67 )        {            message.setText("就绪");            dataspace.setText("");        }                        //        else if(keycode == 110)        {            String key = ".";            dataspace.setText(addnum(key));        }                //加号        else if(keycode == 107)        {            String key = "+";            dataspace.setText(addnum(key));        }                //减号        else if(keycode == 109)        {            String key = "-";            dataspace.setText(addnum(key));        }                //乘号        else if(keycode == 106)        {            String key = "*";            dataspace.setText(addnum(key));        }                                        //除号        else if(keycode == 111)        {            String key = "/";            dataspace.setText(addnum(key));        }                //数字7        else if(keycode == 103 || keycode == 55)        {            String key = "7";            dataspace.setText(addnum(key));        }                        //数字8        else if(keycode == 104 || keycode == 56)        {            String key = "8";            dataspace.setText(addnum(key));        }                        //数字9        else if(keycode == 105 || (keycode == 57  && !e.isShiftDown()))        {            String key = "9";            dataspace.setText(addnum(key));        }                                //数字4        else if(keycode == 100 || keycode == 52)        {            String key = "4";            dataspace.setText(addnum(key));        }                        //数字5        else if(keycode == 101 || keycode == 53)        {            String key = "5";            dataspace.setText(addnum(key));        }                        //数字6        else if(keycode == 102 || keycode == 54)        {            String key = "6";            dataspace.setText(addnum(key));        }                        //数字1        else if(keycode == 97 || keycode == 49)        {            String key = "1";            dataspace.setText(addnum(key));        }                        //数字2        else if(keycode == 98 || keycode == 50)        {            String key = "2";            dataspace.setText(addnum(key));        }                        //数字3        else if(keycode == 99 || keycode == 51)        {            String key = "3";            dataspace.setText(addnum(key));        }                        //数字0        else if(keycode == 96 || (keycode == 48 && !e.isShiftDown()))        {            String key = "0";            dataspace.setText(addnum(key));        }                //按下R        else if(keycode == 82)        {            message.setText("计算得到的结果为:");            ScriptEngineManager sem = new ScriptEngineManager();                    ScriptEngine se = sem.getEngineByName("js");            try            {                    int leng = dataspace.getText().length();                if(leng==0)                {                    message.setText("你好像没输入数据哦!");                                                        }                else                {                                DecimalFormat df = new DecimalFormat("#.##"); //设置数据格式                     Object  result = se.eval(dataspace.getText());                    double value =http://www.mamicode.com/ Double.parseDouble(df.format(result));                     String valuestr = String.valueOf(value);                    dataspace.setText(valuestr);                }            }            catch (ScriptException evt)            {                message.setText("表达式似乎有错呢!请重新编辑");                }            catch(NumberFormatException evt)            {                message.setText("除数不能为0哦,请重新编辑");            }        }                //按下Backspace                else if (keycode == 8)                {                    message.setText("就绪");                    String data = dataspace.getText().trim();                    if(data.length()>0)                    {                    if(data.charAt(0) != ‘-‘)                    {                        if(data.length() >1)                        {                            if(data.charAt(data.length() - 2) == ‘.‘)                            {                                data = data.substring(0,data.length() -1);                                dataspace.setText(data);                            }                            data = data.substring(0,data.length() - 1);                            dataspace.setText(data);                        }                            else if(data.length() == 1)                        {                            dataspace.setText("");                        }                    }                    else if(data.charAt(0) == ‘-‘)                    {                        if(data.length() >2)                        {                            if(data.charAt(data.length() - 2) == ‘.‘)                            {                                data = data.substring(0,data.length() -1);                                dataspace.setText(data);                            }                            data = data.substring(0,data.length() - 1);                            dataspace.setText(data);                        }                            else if(data.length() == 2)                        {                            dataspace.setText("0");                        }                    }                    else if(data =http://www.mamicode.com/="0")                    {                        dataspace.setText("");                    }                    }                    else                    {}                }                                //左括号                else if(keycode == 57 && e.isShiftDown())                {                    String key = "(";                    dataspace.setText(addnum(key));                }                                //右括号                else if(keycode == 48 && e.isShiftDown())                {                    String key = ")";                    dataspace.setText(addnum(key));                }            }    @Override    public void keyPressed(KeyEvent e) {        // TODO 自动生成的方法存根            }}

小学期自己写的一个程序,功能简单。没有bug