用java编写一个简易的计算器,要求能进行加减乘除运算,通过鼠标点击按键交互,并使用边界布局
时间: 2023-06-20 14:09:32 浏览: 104
以下是一个使用边界布局的简易计算器示例代码,可以进行加减乘除运算:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double num1, num2, result;
private String operator;
public Calculator() {
super("Calculator");
// 初始化组件
display = new JTextField(20);
display.setEditable(false);
display.setHorizontalAlignment(SwingConstants.RIGHT);
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
}
// 设置布局
Container container = getContentPane();
container.setLayout(new BorderLayout(5, 5));
container.add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
for (int i = 0; i < buttonLabels.length; i++) {
buttonPanel.add(buttons[i]);
}
container.add(buttonPanel, BorderLayout.CENTER);
// 设置窗口
setSize(300, 250);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.matches("[0-9.]")) {
// 数字或小数点
if (operator == null) {
display.setText(display.getText() + command);
} else {
if (num2 == 0 && command.equals(".")) {
display.setText(num1 + operator + "0" + command);
} else {
display.setText(display.getText() + command);
}
}
} else if (command.matches("[+\\-*/]")) {
// 加减乘除
if (operator != null) {
num2 = Double.parseDouble(display.getText());
result = calculate();
display.setText(result + "");
num1 = result;
} else {
num1 = Double.parseDouble(display.getText());
}
operator = command;
} else if (command.equals("=")) {
// 等于号
num2 = Double.parseDouble(display.getText());
result = calculate();
display.setText(result + "");
num1 = result;
operator = null;
} else if (command.equals("C")) {
// 清除
num1 = num2 = result = 0;
operator = null;
display.setText("");
}
}
private double calculate() {
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
return num1 / num2;
default:
return 0;
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行后,可以看到一个简易的计算器界面,并且可以通过鼠标点击按键进行交互:
阅读全文