用swing类来实现简单的计算器编写
代码如下
public class Count extends JFrame{
private static final long serialVersionUID = 1L;
private JTextField txtResult;
private JPanel p;
private String[] number = {"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
private JButton button[] = new JButton[number.length];
private double result = 0; //定义计算机结果的变量
private String lastCommand = "="; //最后一个操作符
private boolean start = true;
//添加底层
public Count() {
super("计算器");
txtResult = new JTextField(20); //文本框
txtResult.setFocusable(false);
this.add(txtResult,BorderLayout.NORTH);
p=new JPanel(new GridLayout(4,4)); //4,4 的网格布局
//循环实例化数组
for (int i = 0; i < button.length; i++) {
button[i] = new JButton(number[i]);
button[i].addActionListener(new ButtonAction());
button[i].addKeyListener(new KeyAction());
p.add(button[i]);
}
this.add(p,BorderLayout.CENTER);
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//计算
public void count(double x ) {
if (lastCommand.equals("+")) {
result+=x;
}else if (lastCommand.equals("-")) {
result -=x;
}else if(lastCommand.equals("*"))
{
result *=x;
}else if (lastCommand.equals("/")) {
result /=x;
}else if (lastCommand.equals("=")) {
result = x;
}
txtResult.setText(""+result);
}
//监听加减乘除
public class ButtonAction implements ActionListener{
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
if (input.equals("+")||input.equals("-")
||input.equals("*")||input.equals("/")||input.equals("=")) {
if (start) {
if (input.equals("-")) {
txtResult.setText(input); //这一块代码有Bug
}else {
lastCommand=input;
}
}else {
count(Double.parseDouble(txtResult.getText())); //获取并强制转化成string 类型
lastCommand =input;
start = true;
}
}else {
if (start) {
txtResult.setText("");
start= false;
}
txtResult.setText(txtResult.getText()+input);
}
}
}
public class KeyAction extends KeyAdapter {
public void actionPerformed(KeyEvent e) {
char key =e.getKeyChar();
//获取数字
if (key=='0'||key=='1'||key=='2'||key=='3'
||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9') {
if (start) {
txtResult.setText("");
start=false;
}
txtResult.setText(txtResult.getText()+key);
}
//操作符
else if (key=='+'||key=='-'||key=='*'||key=='/'||key=='=') {
if (start) {
if (key=='+') {
txtResult.setText(String.valueOf(key));
start = false;
}else {
lastCommand=String.valueOf(key);
}
}else {
count(Double.parseDouble(txtResult.getText()));
lastCommand=String.valueOf(key);
start = true;
}
}
}
}
public static void main(String[] args) {
new Count();
}