生成一个java计算器的可视界面代码,自己输入运算数和运算符号
时间: 2024-09-07 18:04:46 浏览: 64
创建一个简单的Java GUI计算器需要使用Swing或JavaFX库。这里我会给出一个基于Swing的例子,因为它是Java的标准GUI库。请注意,这只是一个基本的示例,实际应用可能需要更复杂的错误处理和用户界面设计。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField[] fields = new JTextField[4];
private JButton[] buttons = new JButton[10];
public SimpleCalculator() {
// 设置窗口标题和大小
setTitle("Simple Calculator");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建输入框和按钮布局
JPanel panel = new JPanel();
for (int i = 0; i < 4; i++) {
fields[i] = new JTextField();
fields[i].setColumns(5);
panel.add(fields[i]);
}
int buttonIndex = 0;
for (String symbol : new String[]{"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "+", "="}) {
buttons[buttonIndex++] = createButton(symbol, i % 4 == 0 ? ActionListenerType.INPUT : ActionListenerType.OP);
panel.add(buttons[buttonIndex - 1]);
}
JButton clearBtn = new JButton("Clear");
clearBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (JTextField field : fields) {
field.setText("");
}
}
});
buttons[buttonIndex++] = clearBtn;
panel.add(clearBtn);
add(panel);
}
private JButton createButton(String symbol, ActionListenerType type) {
JButton button = new JButton(symbol);
button.addActionListener((ActionEvent e) -> {
switch (type) {
case INPUT:
JTextField targetField = fields[(int) e.getActionCommand().charAt(0) - '0'];
targetField.setText(targetField.getText() + symbol);
break;
case OP:
JTextField leftField = fields[(int) e.getActionCommand().charAt(0) - '0'];
JTextField rightField = fields[(int) e.getActionCommand().charAt(1) - '0'];
double leftValue = Double.parseDouble(leftField.getText());
double rightValue = Double.parseDouble(rightField.getText());
double result = 0;
switch (e.getActionCommand()) {
case "+":
result = leftValue + rightValue;
break;
case "-":
result = leftValue - rightValue;
break;
case "*":
result = leftValue * rightValue;
break;
case "/":
if (rightValue != 0)
result = leftValue / rightValue;
else
JOptionPane.showMessageDialog(null, "Error: Division by zero is not allowed.");
break;
}
leftField.setText(Double.toString(result));
break;
}
});
return button;
}
enum ActionListenerType {
INPUT,
OP
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
```
在这个例子中,我们创建了一个包含数字、操作符和清除按钮的简单计算器界面。用户可以输入数字,点击运算符按钮执行计算,结果会显示在相应的输入字段中。当点击"="按钮时,会尝试执行运算并更新结果。
阅读全文