package com.mine;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calc extends JFrame {
Panel pan1 = new Panel();
Panel pan2 = new Panel();
Panel pan3 = new Panel();
JButton[] btn = new JButton[17];
JTextField txt;
static String sign; //用来存储计算符
static double temp ; //存储计算结果
String[] str = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3",
"*", "0", ".", "=", "/", "清空" }; //String数组用来存储按键信息
public Calc(String name) {
super(name);
pan1.setLayout(new BorderLayout());
pan2.setLayout(new GridLayout(4, 4));
pan3.setLayout(new BorderLayout());
txt = new JTextField();
this.setVisible(true);
this.setSize(175, 220);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
for (int i = 0; i < btn.length; i++) {
btn[i] = new JButton(str[i]);
}
for (int j = 0; j < btn.length; j++) {
pan2.add(btn[j]);
}
for (int i = 0; i <btn.length; i++) {
btn[i].addActionListener(new buttonlistener());//添加监听器
}
pan1.add(txt, "North");
pan3.add(btn[16]);
this.add(pan1, "North");
this.add(pan2, "Center");
this.add(pan3, "South");
}
class buttonlistener implements ActionListener{ //按钮监听事件,根据按键给不同德结果
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource(); //获得数据源
if (btn.getText().equals("=")) {
Numeration();
txt.setText(String.valueOf(temp));
sign = "";
} else if (btn.getText().equals("+")) {
Numeration();
txt.setText("");
sign = "+";
} else if (btn.getText().equals("-")) {
Numeration();
txt.setText("");
sign = "-";
} else if (btn.getText().equals("/")) {
Numeration();
txt.setText("");
sign = "/";
} else if (btn.getText().equals("*")) {
Numeration();
txt.setText("");
sign = "*";
} else {
txt.setText(txt.getText() + btn.getText()); //文本框显示数字
if (btn.getText() == "清空"){//点击清空按钮,则把所有信息重新赋为空
txt.setText("");
sign="";
temp=0;
}
}
}
public void Numeration() {//编写具体计算方法
if (sign == "+"){
temp += Double.parseDouble(txt.getText());
}else if (sign == "-"){
temp -= Double.parseDouble(txt.getText());
}else if (sign == "*"){
temp *= Double.parseDouble(txt.getText());
}else if (sign == "/"){
temp /= Double.parseDouble(txt.getText());
}else{ //如果按=,则
temp = Double.parseDouble(txt.getText());
}
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
Calc c = new Calc("计算器");
}
}
简易计算器
最新推荐文章于 2023-03-18 20:29:55 发布