package unit_one;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class model {
JFrame f = new JFrame("计算器");
JTextField t = new JTextField(20);
JButton clean = new JButton("清空");
JButton[] b = new JButton[16];
String sr = "123+456-789*0.=/";
JPanel p1 = new JPanel(new FlowLayout());//建立流式布局的面板p1
JPanel p2 = new JPanel(new GridLayout(4,4));//建立4x4表格布局的面板p2
void input() {
for (int i = 0; i < b.length; i++) {
b[i] = new JButton(sr.charAt(i) + "");
b[i].addActionListener(new react()); //为每个按钮按钮添加时间监听
}
f.setSize(350,300); //设置窗体大小
p1.add(t);
clean.setBackground(Color.pink);//为“清空”键设置颜色
p1.add(clean);/将“清空”键加入面板p1
for (JButton jButton : b) {
jButton.setBackground(Color.cyan);//为每个按钮添加背景颜色
p2.add(jButton);//将每个按钮加入p2面板
}
f.setLayout(new BorderLayout());//将窗体设置为方位布局
f.add(p1,BorderLayout.NORTH);//将p1放在北部
f.add(p2,BorderLayout.CENTER);//将p2放在中间
f.setVisible(true);//窗体可视化
clean.addActionListener(new react());//为“清空”键增加事件监听
}
String n1;
String n2;
double end;//用于存放最后结果
String operat;//用于存放运算符
String number="";//用于存放文本域中的内容
class react implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object c=e.getSource();
String text=e.getActionCommand();
if(text.equals("=")){
switch (operat) {
case "+":
end = Double.parseDouble(n1) + Double.parseDouble(n2);
t.setText(end + "");
n1 = null;
break;
case "-":
end = Double.parseDouble(n1) - Double.parseDouble(n2);
t.setText(end + "");
n1 = null;
break;
case "*":
end = Double.parseDouble(n1) * Double.parseDouble(n2);
t.setText(end + "");
n1 = null;
break;
case "/":
end = Double.parseDouble(n1) / Double.parseDouble(n2);
t.setText(end + "");
n1 = null;
break;
}
number="";
}else if(text.equals("+")){
operat="+";
number=number+text;
t.setText(number);
}else if(text.equals("-")) {
operat = "-";
number=number+text;
t.setText(number);
}else if(text.equals("*")) {
operat = "*";
number=number+text;
t.setText(number);
}else if(text.equals("/")) {
operat = "/";
number = number + text;
t.setText(number);
}
else if(c==clean){
t.setText("");
n1=null;
n2=null;
operat=null;
number="";
}
else{
if(n1==null) {
n1 = text;
}else {
n2=text;
}
number=number+text;
t.setText(number);
}
}
}
}
public class Calculator {
public static void main(String[] args){
model m1=new model();
m1.input();
}
}
实现效果如图所示:
注:此计算器只能实现个位数的加减乘除运算!!!