首页下载资源后端基于JavaSwing的简单计算器

ZIP基于JavaSwing的简单计算器

qq_508018748.03KB需要积分:1

资源文件列表:

demo-2.zip 大约有16个文件
  1. demo-2/
  2. demo-2/.idea/
  3. demo-2/.idea/.gitignore 184B
  4. demo-2/.idea/misc.xml 278B
  5. demo-2/.idea/modules.xml 259B
  6. demo-2/.idea/runConfigurations.xml 346B
  7. demo-2/.idea/workspace.xml 2.47KB
  8. demo-2/demo-2.iml 433B
  9. demo-2/out/
  10. demo-2/out/production/
  11. demo-2/out/production/demo-2/
  12. demo-2/out/production/demo-2/Calculator$1.class 178B
  13. demo-2/out/production/demo-2/Calculator$ButtonListener.class 2.42KB
  14. demo-2/out/production/demo-2/Calculator.class 2.06KB
  15. demo-2/src/
  16. demo-2/src/Calculator.java 2.82KB

资源介绍:

基于JavaSwing的简单计算器
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Calculator extends JFrame { private JTextField display; public Calculator() { super("简易计算器"); // 设置布局 setLayout(new BorderLayout()); // 创建显示区域 display = new JTextField(); display.setEditable(false); add(display, BorderLayout.NORTH); display.setFont(new Font("Serif", Font.PLAIN, 40)); add(display, BorderLayout.NORTH); // 创建面板以放置按钮 JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); // 按钮数组 String[] buttons = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "C", "=", "+" }; // 添加按钮到面板 for (String buttonText : buttons) { JButton button = new JButton(buttonText); button.addActionListener(new ButtonListener()); panel.add(button); } // 将面板添加到框架 add(panel, BorderLayout.CENTER); // 设置窗口属性 setSize(300, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } // 按钮监听器 private class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if ("C".equals(command)) { display.setText(""); } else if ("=".equals(command)) { try { String text = display.getText().replace('÷', '/').replace('×', '*'); double result = evaluateExpression(text); display.setText(String.valueOf(result)); } catch (Exception ex) { display.setText("错误"); } } else { display.setText(display.getText() + command); } } private double evaluateExpression(String expression) { // 这里可以使用脚本引擎来计算表达式 javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager(); javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript"); try { return ((Number) engine.eval(expression)).doubleValue(); } catch (javax.script.ScriptException e) { throw new RuntimeException(e); } } } public static void main(String[] args) { new Calculator(); } }
100+评论
captcha