eclipse简易计算器java
时间: 2024-01-06 20:25:39 浏览: 93
以下是一个简易的Java计算器程序示例,使用Eclipse进行开发:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField displayField;
private JButton[] numberButtons;
private JButton[] operatorButtons;
private JButton equalsButton;
private JButton clearButton;
private double num1, num2, result;
private String operator;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(new BorderLayout());
displayField = new JTextField();
displayField.setHorizontalAlignment(JTextField.RIGHT);
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
buttonPanel.add(numberButtons[i]);
}
operatorButtons = new JButton[4];
operatorButtons[0] = new JButton("+");
operatorButtons[1] = new JButton("-");
operatorButtons[2] = new JButton("*");
operatorButtons[3] = new JButton("/");
for (int i = 0; i < 4; i++) {
operatorButtons[i].addActionListener(this);
buttonPanel.add(operatorButtons[i]);
}
equalsButton = new JButton("=");
equalsButton.addActionListener(this);
buttonPanel.add(equalsButton);
clearButton = new JButton("C");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == clearButton) {
displayField.setText(""); } else if (source == equalsButton) {
num2 = Double.parseDouble(displayField.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
displayField.setText(String.valueOf(result));
} else {
for (int i = 0; i < 10; i++) {
if (source == numberButtons[i]) {
displayField.setText(displayField.getText() + i);
break;
}
}
for (int i = 0; i < 4; i++) {
if (source == operatorButtons[i]) {
num1 = Double.parseDouble(displayField.getText());
operator = operatorButtons[i].getText();
displayField.setText("");
break;
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Calculator();
}
});
}
}
```
阅读全文