基于swing生成计算器带注释
时间: 2023-08-13 15:05:05 浏览: 96
Java swing实现的计算器功能完整实例
好的,我可以为您提供一个基于Swing生成计算器的代码示例,其中包含注释,方便您阅读和理解。
```java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
// 创建需要用到的组件
JTextField resultField = new JTextField();
JPanel buttonPanel = new JPanel();
// 定义计算器上的按钮
String[] buttonLabels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "C", "=", "+" };
JButton[] buttons = new JButton[buttonLabels.length];
// 记录计算器的状态和操作,以便进行计算
int firstNumber = 0;
int secondNumber = 0;
String operation = "";
boolean newNumber = true;
public Calculator() {
// 设置计算器的标题和大小
setTitle("Calculator");
setSize(300, 300);
// 设置结果文本框不可编辑
resultField.setEditable(false);
// 将计算器的组件添加到面板中
Container contentPane = getContentPane();
contentPane.add(resultField, BorderLayout.NORTH);
contentPane.add(buttonPanel, BorderLayout.CENTER);
// 设置面板的布局为网格布局
buttonPanel.setLayout(new GridLayout(4, 4));
// 创建按钮并添加到面板中,并为按钮添加事件监听器
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
}
// 处理按钮事件
public void actionPerformed(ActionEvent e) {
String buttonLabel = e.getActionCommand();
// 如果按下的是数字键
if (buttonLabel.matches("\\d")) {
if (newNumber) {
resultField.setText(buttonLabel);
newNumber = false;
} else {
resultField.setText(resultField.getText() + buttonLabel);
}
}
// 如果按下的是操作符键
if (buttonLabel.matches("\\+|\\-|\\*|\\/")) {
firstNumber = Integer.parseInt(resultField.getText());
operation = buttonLabel;
newNumber = true;
}
// 如果按下的是等号键
if (buttonLabel.equals("=")) {
secondNumber = Integer.parseInt(resultField.getText());
int result = 0;
if (operation.equals("+")) {
result = firstNumber + secondNumber;
}
if (operation.equals("-")) {
result = firstNumber - secondNumber;
}
if (operation.equals("*")) {
result = firstNumber * secondNumber;
}
if (operation.equals("/")) {
result = firstNumber / secondNumber;
}
resultField.setText(Integer.toString(result));
newNumber = true;
}
// 如果按下的是清除键
if (buttonLabel.equals("C")) {
resultField.setText("");
newNumber = true;
firstNumber = 0;
secondNumber = 0;
operation = "";
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
}
```
希望这份代码能对您有所帮助!
阅读全文