简单计算器的实现

使用Java设计一个简单的计算器,能够实现加、减、乘、除运算,设计好后的计算器界面如下
简单计算器的实现_第1张图片
要点:
1、通过JButton里的getText()方法,得到JButton上的字符串,然后单独用个String类型的变量存储用户期望计算表达式;

2、在获取1+2/3这个要计算的式子后,按下等于符号,要求计算出正确结果,在Java里面,没有函数能够根据计算表达式就能得到结果,但在JavaScript里面却有一个Object eval(String a)能够返回结果,在Java里有一个已经实现好了的JavaScript,通过如下方式构造:

ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("JavaScript");
//如上,利用默认构造的ScriptEngineManager调好ScriptEngine的参数,在getEngineByName("JavaScript")这个函数中,为其传递的字符串要为JavaScript才能正常构造出engine——一个JavaScript,这个还有其他构造方法,详见API
//如下所示调用函数eval
Object o = engine.eval("1+2/3");
System.out.println(o);//自动调用Object里的toString()方法,但是JTextField里的setText却不能为其调用,必须加上screen.toString()才行

以下是简单计算器的实现代码

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

class test extends JFrame implements ActionListener
{
    JTextField screen;
    JButton bt[][] = new JButton[4][4];
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName("JavaScript");
    String alu = "";

    public test()
    {
        screen = new JTextField("caculate area");
        screen.setSize(2, 15);
        screen.setHorizontalAlignment(JTextField.TRAILING);
        screen.setEditable(false);

        String bt_char[][] = {{"1", "2", "3", "+"},
                              {"4", "5", "6", "-"},
                              {"7", "8", "9", "*"},
                              {".", "0", "=", "/"}};
        for(int i = 0; i < bt_char.length; i ++)
            for(int j = 0; j < bt_char[1].length; j ++)
            {
                bt[i][j] = new JButton(bt_char[i][j]);
                bt[i][j].addActionListener(this);
            }

        GridLayout layout = new GridLayout(4, 4);
        layout.setVgap(10);
        layout.setHgap(10);
        JPanel p1 = new JPanel(layout);
        for(int i = 0; i < bt_char.length; i ++)
            for(int j = 0; j < bt_char[1].length; j ++)
                p1.add(bt[i][j]);

        getContentPane().add(screen);
        getContentPane().add(p1);
        setLayout(new GridLayout(2, 1));
        pack();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        JButton selectButton = (JButton)e.getSource();
        if(selectButton != bt[3][2])
        {
            alu =  alu + selectButton.getText();
            screen.setText(alu);
        }
        else
        {
            try{
                screen.setText(engine.eval(alu).toString());
                alu = screen.getText();
            }
            catch(ScriptException a)
            {
                screen.setText(a.getMessage());
            }
        }
    }

    public static void main(String arg[])
    {
        new test();
    }
}

你可能感兴趣的:(简单计算器的实现)