package cn.edu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Calculator extends MouseAdapter {
JFrame list;
// Container con;
JTextField show;
JTextField realshow;
JButton[] jbNum = new JButton[10];
JPanel jpMain; // 主面板
JPanel jpRight; // 右子面板主要用于存放运算符和等号
JPanel jpLight; // 左子面板用于存放数字,符号, “.”
JButton dight; // 小数点
JButton recip; // 正负号
JButton add; // 加号
JButton sub; // 减号
JButton multiply; // 乘号
JButton divide; // 除号
JButton power; // 求幂
JButton cos; // cos
JButton sin; // sin
JButton delete; // delete
JButton ce; // 清除
JButton equal; // 等于
JButton mod; // 取余
JButton sqrt; // sqrt
double sum = 0; // 临时结果
boolean b = false; // 监控运算符是否被点击,错误是否出现,用于实现下一次点击按钮时清空
operator i = operator.un; // 记录等号符点击前某一运算符点击次数,用于实现连加或者连减等
int op; // 记录操作符
// 操作符一包括+-*/%^
enum operator {
add, sub, mul, div, mod, pow, sin, cos, sqrt, delete, un
}
void display() {
// 创建主窗口,添加一个Text框,
list = new JFrame("计算器");
list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list.setSize(360, 230);
list.setLocation(400, 300);
list.setBackground(Color.LIGHT_GRAY); // 设置窗口背景颜色
list.setResizable(false);
list.setLayout(new FlowLayout(FlowLayout.CENTER));
show = new JTextField(31);
realshow = new JTextField(31);
realshow.setHorizontalAlignment(JTextField.RIGHT); // 文本框内文字右对齐
realshow.setEditable(false); // 文本框不可编辑
list.add(realshow);
// 创建面板并设置布局
jpMain = new JPanel();
jpRight = new JPanel();
jpLight = new JPanel();
jpMain.setLayout(new GridLayout(1, 2));
jpRight.setLayout(new GridLayout(4, 3, 3, 3));
jpLight.setLayout(new GridLayout(4, 3, 3, 3));
list.add(jpMain);
jpMain.add(jpLight);
jpMain.add(jpRight);
// 创建0~9按钮对象
for (int i = 9; i >= 0; i--) {
jbNum[i] = new JButton(String.valueOf(i));
jbNum[i].setForeground(Color.BLUE);
jpLight.add(jbNum[i]);
jbNum[i].addMouseListener(this);
}
add = new JButton("+");
sub = new JButton("-");
multiply = new JButton("*");
divide = new JButton("/");
power = new JButton("x^y");
sin = new JButton("sin");
cos = new JButton("cos");
delete = new JButton("<");
ce = new JButton("CE");
equal = new JButton("=");
mod = new JButton("%");
sqrt = new JButton("sqrt");
jpRight.add(divide);
jpRight.add(sqrt);
jpRight.add(delete);
jpRight.add(multiply);
jpRight.add(sin);
jpRight.add(mod);
jpRight.add(sub);
jpRight.add(cos);
jpRight.add(ce);
jpRight.add(add);
jpRight.add(power);
jpRight.add(equal);
// 给所有按钮注册监听器
dight = new JButton(".");
recip = new JButton("1/C");
jpLight.add(recip);
jpLight.add(dight);
add.addMouseListener(this);
sub.addMouseListener(this);
multiply.addMouseListener(this);
divide.addMouseListener(this);
power.addMouseListener(this);
sin.addMouseListener(this);
cos.addMouseListener(this);
delete.addMouseListener(this);
ce.addMouseListener(this);
equal.addMouseListener(this);
mod.addMouseListener(this);
sqrt.addMouseListener(this);
dight.addMouseListener(this);
recip.addMouseListener(this);
list.setVisible(true);
}