gui 设计的简单计算器 java_Java实现GUI计算器(完整版)
时间: 2023-12-02 14:02:55 浏览: 86
好的,我会尽力回答您的问题。下面是一个简单的Java GUI计算器的实现代码,您可以参考一下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorGUI implements ActionListener {
private JFrame frame;
private JPanel panel;
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 char operator;
public CalculatorGUI() {
frame = new JFrame("Calculator");
panel = new JPanel();
textField = new JTextField(20);
buttons = new JButton[buttonLabels.length];
num1 = 0.0;
num2 = 0.0;
result = 0.0;
operator = ' ';
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
panel.setLayout(new GridLayout(4, 4, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(textField, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
public static void main(String[] args) {
CalculatorGUI calculator = new CalculatorGUI();
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
if (e.getSource() == buttons[i]) {
String buttonLabel = buttonLabels[i];
if (buttonLabel.matches("[0-9.]")) {
if (operator == ' ') {
num1 = Double.parseDouble(textField.getText() + buttonLabel);
textField.setText(Double.toString(num1));
} else {
num2 = Double.parseDouble(textField.getText() + buttonLabel);
textField.setText(Double.toString(num2));
}
} else if (buttonLabel.matches("[/*\\-+]")) {
operator = buttonLabel.charAt(0);
} else if (buttonLabel.equals("=")) {
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textField.setText(Double.toString(result));
num1 = result;
num2 = 0.0;
operator = ' ';
} else if (buttonLabel.equals("C")) {
num1 = 0.0;
num2 = 0.0;
result = 0.0;
operator = ' ';
textField.setText("");
}
break;
}
}
}
}
```
这个代码实现了一个基本的四则运算的计算器功能,界面简单,易于操作。您可以根据自己的需求进行修改和扩展。希望能对您有所帮助。
阅读全文