Java swing生成一个包括10个数字(0~9)按钮和4个运算符(加、减、乘、除)按钮,以及等号和清空两个辅助按钮,还有一个显示输入输出的文本框的计算器代码
时间: 2023-06-04 17:02:32 浏览: 184
好的,以下是用Java Swing实现一个简单的计算器的代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField;
private JButton[] numberButtons;
private JButton[] operatorButtons;
private JButton equalsButton, clearButton;
private String currentDisplayValue = "";
private String currentOperator = "";
private double currentResult = 0.0;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
inputField = new JTextField();
inputField.setEditable(false);
panel.add(inputField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
buttonPanel.add(numberButtons[i]);
}
operatorButtons = new JButton[4];
operatorButtons[0] = new JButton("+");
operatorButtons[1] = new JButton("-");
operatorButtons[2] = new JButton("*");
operatorButtons[3] = new JButton("/");
for (int i = 0; i < 4; i++) {
operatorButtons[i].addActionListener(this);
buttonPanel.add(operatorButtons[i]);
}
equalsButton = new JButton("=");
equalsButton.addActionListener(this);
buttonPanel.add(equalsButton);
clearButton = new JButton("C");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
panel.add(buttonPanel, BorderLayout.CENTER);
setContentPane(panel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
currentDisplayValue += String.valueOf(i);
inputField.setText(currentDisplayValue);
}
}
for (int i = 0; i < 4; i++) {
if (e.getSource() == operatorButtons[i]) {
currentOperator = operatorButtons[i].getText();
if (!currentDisplayValue.equals("")) {
currentResult = Double.parseDouble(currentDisplayValue);
currentDisplayValue = "";
}
}
}
if (e.getSource() == equalsButton) {
if (!currentDisplayValue.equals("")) {
double currentValue = Double.parseDouble(currentDisplayValue);
if (currentOperator.equals("+")) {
currentResult += currentValue;
} else if (currentOperator.equals("-")) {
currentResult -= currentValue;
} else if (currentOperator.equals("*")) {
currentResult *= currentValue;
} else if (currentOperator.equals("/")) {
currentResult /= currentValue;
}
currentDisplayValue = "";
}
inputField.setText(String.valueOf(currentResult));
}
if (e.getSource() == clearButton) {
currentDisplayValue = "";
currentOperator = "";
currentResult = 0.0;
inputField.setText("");
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
在代码中,我们使用了JFrame和JPanel来创建界面,使用JButton来添加按钮。同时,我们还使用了ActionListener来响应按钮的事件,实现了简单的计算功能。
注意在条件判断中通过getText()方法获取operatorButtons[i]按钮上的文本。
阅读全文