抱歉,之前的代码确实没有实现计算功能。以下是对代码进行完善后的示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame {
private JTextField textField;
private double num1;
private double num2;
private char operator;
private boolean isOperatorPressed = false;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
getContentPane().setLayout(new BorderLayout());
textField = new JTextField();
textField.setFont(new Font("Arial", Font.PLAIN, 20));
textField.setEditable(false);
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.BOLD, 18));
button.addActionListener(new ButtonListener());
panel.add(button);
}
add(panel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
if (buttonText.matches("[0-9.]")) {
handleNumericInput(buttonText);
} else {
handleOperatorInput(buttonText);
}
}
}
private void handleNumericInput(String buttonText) {
String currentText = textField.getText();
textField.setText(currentText + buttonText);
}
private void handleOperatorInput(String buttonText) {
if (!isOperatorPressed) {
num1 = Double.parseDouble(textField.getText());
operator = buttonText.charAt(0);
textField.setText("");
isOperatorPressed = true;
} else {
num2 = Double.parseDouble(textField.getText());
double result = calculate(num1, num2, operator);
textField.setText(String.valueOf(result));
num1 = result;
operator = buttonText.charAt(0);
isOperatorPressed = false;
}
}
private double calculate(double num1, double num2, char operator) {
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
JOptionPane.showMessageDialog(this, "除数不能为0", "错误", JOptionPane.ERROR_MESSAGE);
}
break;
}
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Calculator();
}
});
}
}
这个计算器可以输入整数和小数,并支持加、减、乘、除运算。当除数为0时,会弹出一个提示框显示错误信息。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |