用java写一个程序,要求编写JFrame程序实现一个计算器,包括十个数字(0-9)按钮和四个运算符(加、减、乘、除)按钮,以及等号和清空两个辅助按钮,还有一个显示输入输出的文本框。程序中使用BorderLayout和GridLayout。
时间: 2024-03-09 17:46:06 浏览: 141
好的,以下是用Java编写的计算器程序:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JButton[] buttons;
private JTextField textField;
private double num1, num2, result;
private char operator;
public Calculator() {
super("Calculator");
// 设置窗口大小和位置
setSize(300, 400);
setLocationRelativeTo(null);
// 设置窗口关闭方式
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建按钮面板和文本框
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4, 5, 5));
textField = new JTextField();
textField.setEditable(false);
// 创建数字按钮和运算符按钮
buttons = new JButton[16];
for (int i = 0; i < 10; i++) {
buttons[i] = new JButton(String.valueOf(i));
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
buttons[10] = new JButton("+");
buttons[11] = new JButton("-");
buttons[12] = new JButton("*");
buttons[13] = new JButton("/");
buttons[14] = new JButton("=");
buttons[15] = new JButton("C");
for (int i = 10; i < 16; i++) {
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
// 添加组件到窗口
add(textField, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
// 显示窗口
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
if (buttonText.equals("+")) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText("");
} else if (buttonText.equals("-")) {
num1 = Double.parseDouble(textField.getText());
operator = '-';
textField.setText("");
} else if (buttonText.equals("*")) {
num1 = Double.parseDouble(textField.getText());
operator = '*';
textField.setText("");
} else if (buttonText.equals("/")) {
num1 = Double.parseDouble(textField.getText());
operator = '/';
textField.setText("");
} else if (buttonText.equals("=")) {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textField.setText(String.valueOf(result));
} else if (buttonText.equals("C")) {
num1 = num2 = result = 0;
operator = ' ';
textField.setText("");
} else {
textField.setText(textField.getText() + buttonText);
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序使用了`JFrame`窗口和`JButton`、`JTextField`等Swing组件,实现了简单的计算器功能。用户可以输入数字和运算符,然后点击等号得到计算结果。同时,用户可以点击C按钮清空输入框。
阅读全文