用Java Swing图形组件轻松开发一个简单的四则运算的图形化计算器写出代码
时间: 2024-05-12 14:17:34 浏览: 111
非常感谢您的问题。以下是代码示例:
```
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 previousValue;
private String previousOperator;
public Calculator() {
setTitle("Calculator");
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(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]);
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String buttonText = event.getActionCommand();
if (buttonText.matches("[0-9]")) {
textField.setText(textField.getText() + buttonText);
} else if (buttonText.equals(".")) {
if (!textField.getText().contains(".")) {
textField.setText(textField.getText() + buttonText);
}
} else if (buttonText.matches("[+\\-*/]")) {
previousValue = Double.parseDouble(textField.getText());
previousOperator = buttonText;
textField.setText("");
} else if (buttonText.equals("=")) {
double currentValue = Double.parseDouble(textField.getText());
double result;
if (previousOperator.equals("+")) {
result = previousValue + currentValue;
} else if (previousOperator.equals("-")) {
result = previousValue - currentValue;
} else if (previousOperator.equals("*")) {
result = previousValue * currentValue;
} else {
result = previousValue / currentValue;
}
textField.setText(Double.toString(result));
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
希望这个代码示例能够帮助你开发一个简单的四则运算的图形化计算器。如果您有任何其他问题,请随时问我,我会尽力回答。
阅读全文