简单计算器实现

时间:2022-12-29 14:44:23

基本思路:边输入边计算,最后显示

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javafx.scene.layout.Border;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Calculator extends JFrame {
private boolean start, flag;
private String lastCommand;
private double result1, result2;
private int count=1;
JButton display;
JPanel panel;

public Calculator() {
setLayout(new BorderLayout());
result1 = 0;
result2 = 0;
start = true;
flag = false;
lastCommand = "=";

display = new JButton(" ");
display.setEnabled(false);
add(display, BorderLayout.NORTH);

ActionListener insert = new InsertAction();
ActionListener command = new CommandListener();
panel = new JPanel(new GridLayout(4, 4));

addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);

addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);

addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);

add(panel, BorderLayout.CENTER);

pack();
setTitle("Calculator");
setResizable(false);
setSize(300, 200);
setLocation(400, 400);
setVisible(true);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}

private void addButton(String label, ActionListener listener) {
Button button = new Button(label);
button.addActionListener(listener);
panel.add(button);
}

private class InsertAction implements ActionListener {// 监听数字按钮

public void actionPerformed(ActionEvent e) {

String input = e.getActionCommand();
display.setText(display.getText() + input);
}
}

private class CommandListener implements ActionListener {// 监听命令按钮

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();
if (flag) {
String[] s;
s = display.getText().split("\\" + lastCommand);
result2 = Double.parseDouble(s[s.length-1]);
System.out.println(result2);
calculator();
if (command.equals("="))
display.setText("" + result1);
else
display.setText(display.getText() + command);

lastCommand = command;
//flag = false;
} else {
result1 = Double.parseDouble(display.getText());
display.setText(display.getText() + command);
lastCommand = command;
flag = true;
}
}
}

public void calculator() {// 进行计算的函数

if (lastCommand.equals("+")) {
result1 += result2;
} else if (lastCommand.equals("-")) {
result1 -= result2;
} else if (lastCommand.equals("*")) {
result1 *= result2;
} else if (lastCommand.equals("/")) {
result1 /= result2;
} else if (lastCommand.equals("=")) {
result1 = result2;
}
}

public static void main(String[] args) {
new Calculator();
}

}
简单计算器实现
简单计算器实现