用Java帮我实现一个程序:模仿着做一个Win10的计算器
时间: 2024-02-25 12:51:58 浏览: 82
好的,我可以帮您实现一个简单的Win10风格的计算器程序。以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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() {
super("Calculator");
display = new JTextField(20);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 20));
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].setFont(new Font("Arial", Font.PLAIN, 20));
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("C")) {
result = 0;
operator = "";
startOfNumber = true;
display.setText("");
} else if (label.equals("=")) {
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());
}
display.setText("" + result);
operator = "";
startOfNumber = true;
} else if (label.equals("+") || label.equals("-") || label.equals("*") || label.equals("/")) {
operator = label;
result = Double.parseDouble(display.getText());
startOfNumber = true;
} else {
if (startOfNumber) {
display.setText(label);
startOfNumber = false;
} else {
display.setText(display.getText() + label);
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序使用Java Swing GUI库创建了一个简单的计算器界面,可以进行加、减、乘、除四种基本运算。您可以根据自己的需要进行修改和扩展。
阅读全文