java实现计算器页面
时间: 2023-08-14 19:06:07 浏览: 97
以下是一个简单的Java计算器页面实现示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator {
JFrame frame;
JTextField textField;
double num1, num2, result;
char operator;
public Calculator() {
frame = new JFrame("Calculator");
frame.getContentPane().setLayout(new BorderLayout());
textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
frame.getContentPane().add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
addButton(buttonPanel, "7");
addButton(buttonPanel, "8");
addButton(buttonPanel, "9");
addButton(buttonPanel, "/");
addButton(buttonPanel, "4");
addButton(buttonPanel, "5");
addButton(buttonPanel, "6");
addButton(buttonPanel, "*");
addButton(buttonPanel, "1");
addButton(buttonPanel, "2");
addButton(buttonPanel, "3");
addButton(buttonPanel, "-");
addButton(buttonPanel, "0");
addButton(buttonPanel, ".");
addButton(buttonPanel, "=");
addButton(buttonPanel, "+");
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private void addButton(Container container, String text) {
JButton button = new JButton(text);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
switch (text) {
case "/":
case "*":
case "-":
case "+":
operator = text.charAt(0);
num1 = Double.parseDouble(textField.getText());
textField.setText("");
break;
case "=":
num2 = Double.parseDouble(textField.getText());
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));
break;
default:
textField.setText(textField.getText() + text);
break;
}
}
});
container.add(button);
}
public static void main(String[] args) {
new Calculator();
}
}
```
该示例使用了Java Swing库构建了一个简单的计算器界面,并实现了基本的加、减、乘、除、等于等计算功能。
阅读全文