/** * 一个计算器,与Windows附件自带计算器的标准版功能、界面相仿。 但还不支持键盘操作。 */ public class MyCalculator extends JFrame implements ActionListener { /** 计算器上的键的显示名字 */ private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" }; /** 计算器上的功能键的显示名字 */ private final String[] COMMAND = { "Backspace", "CE", "C" }; /** 计算器左边的M的显示名字 */ private final String[] M = { " ", "MC", "MR", "MS", "M+" }; /** 计算器上键的按钮 */ private JButton keys[] = new JButton[KEYS.length]; /** 计算器上的功能键的按钮 */ private JButton commands[] = new JButton[COMMAND.length]; /** 计算器左边的M的按钮 */ private JButton m[] = new JButton[M.length]; /** 计算结果文本框 */ private JTextField resultText = new JTextField("0"); // 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字 private boolean firstDigit = true; // 计算的中间结果。 private double resultNum = 0.0; // 当前运算的运算符 private String operator = "="; // 操作是否合法 private boolean operateValidFlag = true; /** * 构造函数 */ public MyCalculator() { super(); // 初始化计算器 init(); // 设置计算器的背景颜色 this.setBackground(Color.LIGHT_GRAY); this.setTitle("计算器");
用java实现计算器功能
最新推荐文章于 2025-03-04 20:38:50 发布