JAVA编程实现一个加减法计算器。可以使用鼠标来完成加减法运算。GUI界面细致精准
时间: 2023-08-14 09:05:18 浏览: 98
以下是一个Java实现加减法计算器的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator implements ActionListener {
JFrame frame;
JTextField textField;
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[5];
JButton addButton, subButton;
JPanel panel;
double num1 = 0, num2 = 0, result = 0;
char operator;
public Calculator() {
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(null);
textField = new JTextField();
textField.setBounds(50, 25, 300, 50);
textField.setEditable(false);
addButton = new JButton("+");
subButton = new JButton("-");
functionButtons[0] = addButton;
functionButtons[1] = subButton;
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
}
panel = new JPanel();
panel.setBounds(50, 100, 300, 250);
panel.setLayout(new GridLayout(4, 4));
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(functionButtons[2]);
panel.add(functionButtons[3]);
panel.add(numberButtons[0]);
panel.add(functionButtons[4]);
panel.add(functionButtons[5]);
for (int i = 0; i < 10; i++) {
numberButtons[i].addActionListener(this);
}
for (int i = 0; i < 5; i++) {
functionButtons[i].addActionListener(this);
}
frame.add(textField);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
}
if (e.getSource() == addButton) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText("");
}
if (e.getSource() == subButton) {
num1 = Double.parseDouble(textField.getText());
operator = '-';
textField.setText("");
}
if (e.getSource() == functionButtons[2]) {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
}
textField.setText(String.valueOf(result));
}
if (e.getSource() == functionButtons[3]) {
textField.setText("");
}
if (e.getSource() == functionButtons[4]) {
String currentText = textField.getText();
if (currentText.length() > 0) {
textField.setText(currentText.substring(0, currentText.length() - 1));
}
}
}
}
```
在这个实现中,我们使用了Java Swing库来创建GUI界面,其中包括一个文本框和数字、运算符按钮。我们还实现了一个ActionListener接口,在用户点击按钮时处理相应的操作,包括将数字添加到文本框中、记录第一个数字和运算符、计算结果等等。
请注意,这只是一个简单的示例代码,可能需要进行更多的测试和优化。
阅读全文