java gui 简易计算器
时间: 2023-12-17 22:03:50 浏览: 146
以下是一个Java Swing的GUI图形用户界面编程设计并编写的简易计算器程序,用户可以通过鼠标或键盘输入参加运算的数值和运算符,进行简单的四则运算:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
private double num1, num2, result;
private String operator;
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("C")) {
textField.setText("");
} else if (label.equals("=")) {
num2 = Double.parseDouble(textField.getText());
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
textField.setText(Double.toString(result));
} else if (label.equals("+") || label.equals("-") || label.equals("*") || label.equals("/")) {
num1 = Double.parseDouble(textField.getText());
operator = label;
textField.setText("");
} else {
textField.setText(textField.getText() + label);
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
阅读全文