用java swing写一个四则运算计算器,在JLabel中选择加减乘除
时间: 2024-04-03 20:31:15 浏览: 126
java swing写的计算器
好的,下面是一个简单的Java Swing四则运算计算器的示例代码。代码中使用了GridLayout布局管理器来布置按钮和文本框,setEditable()方法设置JTextField不可编辑,addActionListener()方法添加按钮点击事件监听器,try-catch语句用来捕获异常并在计算出错时显示错误信息。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JPanel panel;
private JTextField textField;
private JLabel label;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
public Calculator() {
setTitle("Calculator");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
textField = new JTextField(10);
textField.setEditable(false);
label = new JLabel(" ");
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
add(textField, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
try {
double result = evaluate(textField.getText());
if (((JCheckBox)buttons[14]).isSelected()) {
result = Math.round(result);
}
textField.setText(Double.toString(result));
} catch (Exception ex) {
textField.setText("");
label.setText("Error: " + ex.getMessage());
}
} else if (command.equals("C")) {
textField.setText("");
label.setText(" ");
} else {
textField.setText(textField.getText() + command);
}
}
private double evaluate(String expression) {
if (!isValidExpression(expression)) {
throw new IllegalArgumentException("Invalid Expression");
}
String[] tokens = expression.split("(?<=[-+*/])|(?=[-+*/])");
double result = Double.parseDouble(tokens[0]);
for (int i = 1; i < tokens.length; i += 2) {
char operator = tokens[i].charAt(0);
double operand = Double.parseDouble(tokens[i+1]);
switch (operator) {
case '+': result += operand; break;
case '-': result -= operand; break;
case '*': result *= operand; break;
case '/':
if (operand == 0) {
throw new ArithmeticException("Division by Zero");
}
result /= operand;
break;
}
}
return result;
}
private boolean isValidExpression(String expression) {
return expression.matches("([-+*/]?\\d+)+([-+*/]\\d+)*");
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
}
```
这个计算器支持四则运算、小数点、清除、计算等功能,并且还有一个复选框可以选择是否四舍五入到整数。可以根据需要进一步修改和完善。
阅读全文