用Java语言创建一个简单的计算器 计算器布局有:顶部有一个显示标签,用于显示计算结果,一个文本框,让用户在中间输入一个整数/双精度浮点数,几个按钮为“CLR”, “ +” , “ -” , “ *” ,“ /”在 底 部。 功能:创建一个累加器状态变量,跟踪当前计算的总体值。点击“CLR”按钮,将累加器值设置为0点击“+”按钮 ,将文本字段值添加到累加器值中点击“-”按钮,从累加器值中减去本字段值,点击“*”按钮,累加器值乘以文本字段值,点击“/”按钮,累加器值除以文本域值。按下按钮后,用新的累加器更新显示标签,清空文本字段。
时间: 2023-09-30 21:04:09 浏览: 166
好的,我可以帮你解答这个问题。下面是Java语言创建一个简单的计算器的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JLabel resultLabel;
private JTextField inputField;
private JButton clearButton;
private JButton addButton;
private JButton subtractButton;
private JButton multiplyButton;
private JButton divideButton;
private double accumulator;
public Calculator() {
super("Calculator");
// Create the components
resultLabel = new JLabel("0.0");
inputField = new JTextField(10);
clearButton = new JButton("CLR");
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
// Add components to the content pane
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel topPanel = new JPanel(new FlowLayout());
topPanel.add(resultLabel);
c.add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(inputField);
c.add(centerPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout());
bottomPanel.add(clearButton);
bottomPanel.add(addButton);
bottomPanel.add(subtractButton);
bottomPanel.add(multiplyButton);
bottomPanel.add(divideButton);
c.add(bottomPanel, BorderLayout.SOUTH);
// Register event handlers
clearButton.addActionListener(this);
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
// Initialize the accumulator
accumulator = 0.0;
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("CLR")) {
accumulator = 0.0;
resultLabel.setText("0.0");
inputField.setText("");
} else {
try {
double value = Double.parseDouble(inputField.getText());
if (command.equals("+")) {
accumulator += value;
} else if (command.equals("-")) {
accumulator -= value;
} else if (command.equals("*")) {
accumulator *= value;
} else if (command.equals("/")) {
accumulator /= value;
}
resultLabel.setText(Double.toString(accumulator));
inputField.setText("");
} catch (NumberFormatException ex) {
inputField.setText("");
}
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.setSize(200, 160);
calc.setVisible(true);
}
}
```
这个程序创建了一个名为 Calculator 的窗口应用程序,其中包含一个显示标签、一个文本框和几个按钮。累加器状态变量 accumulator 跟踪当前计算的总体值,初始化为 0.0。点击 CLR 按钮将累加器值设置为 0.0,点击 + 按钮将文本字段值添加到累加器值中,点击 - 按钮从累加器值中减去文本字段值,点击 * 按钮,累加器值乘以文本字段值,点击 / 按钮,累加器值除以文本字段值。按下按钮后,用新的累加器更新显示标签,清空文本字段。
阅读全文