java设计和编写一个简易的计算器:实现计算器的界面;实现计算按钮不同的计算功能;显示计算器按钮运算后的结果。要求:按钮C在输入框旁边,剩下的按钮顺序为 1 2 3 + 4 5 6 - 7 8 9 * 0 . = /
时间: 2023-11-27 19:49:49 浏览: 133
以下是一个简单的Java计算器的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private double num1, num2, result;
private String operator;
public Calculator() {
super("Calculator");
setLayout(new BorderLayout());
// 创建显示框
display = new JTextField("0");
display.setEditable(false);
add(display, BorderLayout.NORTH);
// 创建按钮面板
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
// 添加按钮
addButton(buttonPanel, "C");
addButton(buttonPanel, "1");
addButton(buttonPanel, "2");
addButton(buttonPanel, "3");
addButton(buttonPanel, "+");
addButton(buttonPanel, "4");
addButton(buttonPanel, "5");
addButton(buttonPanel, "6");
addButton(buttonPanel, "-");
addButton(buttonPanel, "7");
addButton(buttonPanel, "8");
addButton(buttonPanel, "9");
addButton(buttonPanel, "*");
addButton(buttonPanel, "0");
addButton(buttonPanel, ".");
addButton(buttonPanel, "=");
addButton(buttonPanel, "/");
add(buttonPanel, BorderLayout.CENTER);
// 添加计算器事件监听器
num1 = 0;
num2 = 0;
result = 0;
operator = "";
}
// 添加按钮方法
private void addButton(Container c, String label) {
JButton button = new JButton(label);
button.addActionListener(this);
c.add(button);
}
// 处理按钮事件
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("C")) {
// 清除显示框
display.setText("0");
num1 = 0;
num2 = 0;
result = 0;
operator = "";
} else if (command.equals("+") || command.equals("-") || command.equals("*") || command.equals("/")) {
// 处理运算符
num1 = Double.parseDouble(display.getText());
operator = command;
display.setText("");
} else if (command.equals("=")) {
// 处理等号
num2 = Double.parseDouble(display.getText());
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
display.setText(String.valueOf(result));
} else {
// 处理数字和小数点
String currentText = display.getText();
if (currentText.equals("0")) {
currentText = "";
}
display.setText(currentText + command);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setSize(300, 300);
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculator.setVisible(true);
}
}
```
该计算器使用 `JTextField` 显示计算结果和输入数字、运算符,使用 `JButton` 添加数字和运算符按钮,使用 `GridLayout` 将按钮添加到面板中。在 `actionPerformed` 方法中,根据不同的按钮处理不同的事件,包括清除显示框、处理运算符、处理等号以及输入数字和小数点等。最后,通过 `JFrame` 显示计算器界面。
阅读全文