java创建一个计算器窗口
时间: 2023-08-09 12:05:08 浏览: 84
JAVA 窗口计算器
可以参考以下代码实现一个简单的Java计算器窗口:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double result = 0;
private String operator = "";
private boolean startOfNumber = true;
public Calculator() {
setTitle("Calculator");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
setVisible(true);
}
private void createComponents() {
display = new JTextField();
display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("+")) {
calculate();
operator = "+";
startOfNumber = true;
} else if (command.equals("-")) {
calculate();
operator = "-";
startOfNumber = true;
} else if (command.equals("*")) {
calculate();
operator = "*";
startOfNumber = true;
} else if (command.equals("/")) {
calculate();
operator = "/";
startOfNumber = true;
} else if (command.equals("=")) {
calculate();
display.setText(String.valueOf(result));
operator = "";
startOfNumber = true;
} else if (command.equals(".")) {
if (startOfNumber) {
display.setText("0.");
startOfNumber = false;
} else if (display.getText().indexOf(".") == -1) {
display.setText(display.getText() + ".");
}
} else {
display.setText(display.getText() + command);
startOfNumber = false;
}
}
private void calculate() {
if (operator.equals("+")) {
result += Double.parseDouble(display.getText());
} else if (operator.equals("-")) {
result -= Double.parseDouble(display.getText());
} else if (operator.equals("*")) {
result *= Double.parseDouble(display.getText());
} else if (operator.equals("/")) {
result /= Double.parseDouble(display.getText());
} else {
result = Double.parseDouble(display.getText());
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这个计算器窗口使用了JFrame作为主窗口,JTextField作为显示屏幕,JPanel和GridLayout布局来创建按钮。实现了基本的加、减、乘、除和等于操作。
阅读全文