用java语言写一个能在eclipse环境中运行的代码,代码内容为写一个窗口,实现计算器的加减乘除功能
时间: 2024-12-13 19:16:48 浏览: 3
在Java中,我们可以创建一个简单的图形用户界面(GUI)计算器来实现基本的加减乘除功能。这里我会提供一个基础的Swing框架示例,它可以在Eclipse环境下运行:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField display;
private JButton[] buttons = new JButton[4]; // 数字0-9
private JButton operatorButtons = new JButton[]{"+", "-", "*", "/"}; // 运算符按钮
private String currentDisplay = "0";
public SimpleCalculator() {
setTitle("简单计算器");
setSize(300, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 6)); // 5行6列布局
for (int i = 0; i < 10; i++) { // 数字按钮
buttons[i] = new JButton(String.valueOf(i));
buttons[i].addActionListener(e -> doOperation());
panel.add(buttons[i]);
}
for (String op : operatorButtons) { // 运算符按钮
JButton button = new JButton(op);
button.addActionListener(e -> {
if (!currentDisplay.isEmpty()) {
double num1 = Double.parseDouble(currentDisplay);
currentDisplay = "";
performOperation(num1, op);
}
});
panel.add(button);
}
display = new JTextField(15);
display.setEditable(false);
display.setHorizontalAlignment(JTextField.CENTER);
panel.add(display);
add(panel);
setVisible(true);
}
private void doOperation() {
String newNumber = display.getText() + buttons[(int) event.getSource().getActionCommand()].getText();
currentDisplay += newNumber;
display.setText(currentDisplay);
}
private void performOperation(double num1, String operator) {
try {
double result = 0;
switch (operator) {
case "+":
result = num1 + Double.parseDouble(currentDisplay);
break;
case "-":
result = num1 - Double.parseDouble(currentDisplay);
break;
case "*":
result = num1 * Double.parseDouble(currentDisplay);
break;
case "/":
result = num1 / Double.parseDouble(currentDisplay);
break;
default:
JOptionPane.showMessageDialog(this, "无效的运算符");
return;
}
currentDisplay = String.format("%.2f", result);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "请输入数字");
currentDisplay = "0";
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new SimpleCalculator());
}
}
阅读全文