本文实例为大家分享了java简单实现计算器的具体代码,供大家参考,具体内容如下
public class Calculator { static ScriptEngine jse = new ScriptEngineManager().getEngineByName(\"JavaScript\"); private static void CreateFrame() { JFrame f = new JFrame(\"计算器\"); f.setSize(600, 500); f.setVisible(true); f.setLayout(new BorderLayout()); f.setLayout(new GridLayout(6, 3)); f.setLocation(300, 150); JTextArea text = new JTextArea(20, 0); f.add(text, BorderLayout.NORTH); JButton but1 = new JButton(\"CE\"); f.add(but1, BorderLayout.PAGE_END); String a[] = { \"=\", \"7\", \"8\", \"9\", \"4\", \"5\", \"6\", \"1\", \"2\", \"3\", \"0\", \"+\", \"-\", \"*\", \"/\", \".\" }; JButton btn[] = new JButton[a.length]; for (int i = 0; i < a.length; i++) { btn[i] = new JButton(a[i]); f.add(btn[i]); } // 功能实现 for (int i = 0; i < a.length; i++) { // 如果不是等于号 if (i != 0) { int j = i; btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String s = btn[j].getText();// 获取文本框内容 text.append(s); } }); } else { // 如果点击等于号 btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // 获取文本框内容 String gongshi = text.getText(); // 计算获取的文本框中的内容 String jieguo = jse.eval(gongshi).toString(); text.setText(\"=\"); text.setText(jieguo); } catch (Exception t) { text.setText(\"\"); } } }); // CE按钮 but1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getSource() == but1) { text.setText(\"\"); } } }); } } } public static void main(String[] args) { SwingUtilities.invokeLater(Calculator::CreateFrame); } }
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。