使用java实现一个计算器页面
时间: 2023-05-22 15:04:42 浏览: 112
好的,以下是一个简单的使用 Java 实现计算器页面的示例代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator implements ActionListener {
private JFrame frame;
private JPanel panel;
private JTextField output;
private JButton[] buttons;
private String[] labels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
private double num1 = 0, num2 = 0, result = 0;
private char op = ' ';
public Calculator() {
frame = new JFrame("Calculator");
panel = new JPanel();
output = new JTextField("");
buttons = new JButton[16];
output.setEditable(false);
output.setHorizontalAlignment(JTextField.RIGHT);
panel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(labels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
frame.getContentPane().add(output, BorderLayout.NORTH);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < 16; i++) {
if (source == buttons[i]) {
if (labels[i].matches("[0-9]")) {
if (op == ' ') {
num1 = num1 * 10 + Integer.parseInt(labels[i]);
output.setText(String.valueOf(num1));
} else {
num2 = num2 * 10 + Integer.parseInt(labels[i]);
output.setText(String.valueOf(num2));
}
} else if (labels[i].equals(".")) {
if (op == ' ') {
num1 = Double.parseDouble(output.getText());
output.setText(output.getText() + ".");
} else {
num2 = Double.parseDouble(output.getText());
output.setText(output.getText() + ".");
}
} else if (labels[i].matches("[/+*-]")) {
op = labels[i].charAt(0);
} else if (labels[i].equals("=")) {
if (op == '+') {
result = num1 + num2;
} else if (op == '-') {
result = num1 - num2;
} else if (op == '*') {
result = num1 * num2;
} else if (op == '/') {
result = num1 / num2;
}
op = ' ';
num1 = result;
num2 = 0;
output.setText(String.valueOf(result));
}
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序使用 JFrame 和 JPanel 实现计算器页面,其中包含一个 JTextField 用于显示计算结果,以及 16 个 JButton 用于接收用户输入的数字和运算符。每当用户点击一个按钮时,程序通过 actionPerformed 方法进行相应的处理,最终实现计算器的基本功能。
阅读全文