Java swing简易计算器
时间: 2023-09-30 15:08:33 浏览: 103
以下一个简单的Java Swing计算器示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleCalculator implements ActionListener {
private JFrame frame;
private JTextField textField;
private JButton[] buttons;
private JPanel buttonPanel;
private String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
private double result = 0;
private String operator = "";
private boolean startOfNumber = true;
public SimpleCalculator() {
frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 200);
textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
buttons = new JButton[buttonLabels.length];
buttonPanel = new JPanel();
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]);
}
frame.add(textField, BorderLayout.NORTH);
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String buttonText = e.getActionCommand();
if (buttonText.matches("[0-9.]")) {
if (startOfNumber) {
textField.setText(buttonText);
startOfNumber = false;
} else {
textField.setText(textField.getText() + buttonText);
}
} else {
if (startOfNumber) {
if (buttonText.equals("-")) {
startOfNumber = false;
textField.setText(buttonText);
} else {
operator = buttonText;
}
} else {
double number = Double.parseDouble(textField.getText());
if (operator.equals("+")) {
result += number;
} else if (operator.equals("-")) {
result -= number;
} else if (operator.equals("*")) {
result *= number;
} else if (operator.equals("/")) {
result /= number;
}
operator = buttonText;
textField.setText("" + result);
startOfNumber = true;
}
}
}
public static void main(String[] args) {
new SimpleCalculator();
}
}
```
该计算器具有基本的加、减、乘、除功能,并且可以处理小数。它还具有一个清除按钮,以便可以清除当前输入的数字。可以通过单击“=”按钮获取结果。
阅读全文