Java图形界面编写简单计算器功能
时间: 2023-08-03 19:08:28 浏览: 89
下面是一个简单的Java图形界面计算器:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double num1, num2;
private char operator;
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 4));
textField = new JTextField("");
add(textField);
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonLabels[i]);
add(buttons[i]);
buttons[i].addActionListener(this);
}
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (input.equals("C")) {
textField.setText("");
num1 = 0;
num2 = 0;
operator = '\0';
} else if (input.equals("+")) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText("");
} else if (input.equals("-")) {
num1 = Double.parseDouble(textField.getText());
operator = '-';
textField.setText("");
} else if (input.equals("*")) {
num1 = Double.parseDouble(textField.getText());
operator = '*';
textField.setText("");
} else if (input.equals("/")) {
num1 = Double.parseDouble(textField.getText());
operator = '/';
textField.setText("");
} else if (input.equals("=")) {
num2 = Double.parseDouble(textField.getText());
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textField.setText(Double.toString(result));
} else {
textField.setText(textField.getText() + input);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这个计算器使用了JFrame和JButton来构建图形界面。它支持加、减、乘、除、小数点和等于号等基本的运算。当用户按下操作符键时,程序会记录下第一个数字和操作符。当用户按下等于号时,程序会记录下第二个数字,并根据操作符计算出结果并显示在文本框中。
阅读全文