用java swing组件实现一个简单的计算器,写出代码
时间: 2023-04-08 19:04:57 浏览: 120
好的,我可以回答这个问题。以下是一个简单的Java Swing计算器的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
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() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
textField = new JTextField(20);
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("C")) {
textField.setText("");
} else if (label.equals("+/-")) {
double value = Double.parseDouble(textField.getText());
value = -value;
textField.setText(Double.toString(value));
} else if (label.equals("%")) {
double value = Double.parseDouble(textField.getText());
value = value / 100;
textField.setText(Double.toString(value));
} else if (label.equals("/") || label.equals("*") || label.equals("-") || label.equals("+")) {
num1 = Double.parseDouble(textField.getText());
operator = label;
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 {
textField.setText(textField.getText() + label);
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器使用了Java Swing组件来创建一个简单的GUI界面。它包括一个文本框和16个按钮,可以进行基本的加、减、乘、除、百分比和正负号计算。
阅读全文