java gui模拟实现一个可视化简单计算器
时间: 2024-01-20 07:04:42 浏览: 104
java GUI 实现的简单 计算器
5星 · 资源好评率100%
好的,我可以为您展示一个简单的Java GUI计算器的实现过程。首先,我们需要创建一个包含数字和操作符的按钮的GUI界面,然后将这些按钮与计算器的操作相对应。下面是一个简单的实现示例:
```
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 display = new JTextField("0");
private double result = 0;
private String operator = "=";
private boolean calculating = true;
public Calculator() {
super("Calculator");
setSize(350, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
String buttonLabels = "789/456*123-0.=+";
for (int i = 0; i < buttonLabels.length(); i++) {
char key = buttonLabels.charAt(i);
if (key == ' ') {
panel.add(new JLabel(""));
} else {
JButton button = new JButton(Character.toString(key));
button.addActionListener(this);
panel.add(button);
}
}
getContentPane().add(BorderLayout.CENTER, panel);
getContentPane().add(BorderLayout.NORTH, display);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String currentButton = ae.getActionCommand();
if ('0' <= currentButton.charAt(0) && currentButton.charAt(0) <= '9') {
if (calculating) {
display.setText(currentButton);
} else {
display.setText(display.getText() + currentButton);
}
calculating = false;
} else {
if (calculating) {
if (currentButton.equals("-")) {
display.setText(currentButton);
calculating = false;
} else {
operator = currentButton;
}
} else {
double x = Double.parseDouble(display.getText());
calculate(x);
operator = currentButton;
calculating = true;
}
}
}
public void calculate(double n) {
if (operator.equals("+")) {
result += n;
} else if (operator.equals("-")) {
result -= n;
} else if (operator.equals("*")) {
result *= n;
} else if (operator.equals("/")) {
result /= n;
} else if (operator.equals("=")) {
result = n;
}
display.setText("" + result);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这个实现创建了一个包含数字和操作符的按钮的GUI界面,当用户点击这些按钮时,程序会根据输入执行计算,并将结果显示在屏幕上。此外,这个实现还包括了一些错误检查和异常处理,以确保程序的正确性和稳定性。
阅读全文