用java语言写一个图形界面化计算器
时间: 2023-04-10 15:03:03 浏览: 124
基于java语言的计算器图形界面设计.doc
好的,以下是一个简单的Java图形界面计算器的代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField displayField;
private JButton[] buttons;
private String[] buttonLabels = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };
private JPanel buttonPanel;
private double num1, num2;
private String operator;
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
displayField = new JTextField(30);
displayField.setEditable(false);
buttons = new JButton[buttonLabels.length];
buttonPanel = new JPanel(new GridLayout(4, 4));
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
getContentPane().add(displayField, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.matches("[0-9]+")) {
displayField.setText(displayField.getText() + command);
} else if (command.equals(".")) {
if (!displayField.getText().contains(".")) {
displayField.setText(displayField.getText() + ".");
}
} else if (command.matches("[+\\-*/=]")) {
if (operator == null) {
num1 = Double.parseDouble(displayField.getText());
operator = command;
displayField.setText("");
} else {
num2 = Double.parseDouble(displayField.getText());
switch (operator) {
case "+":
num1 += num2;
break;
case "-":
num1 -= num2;
break;
case "*":
num1 *= num2;
break;
case "/":
num1 /= num2;
break;
}
if (command.equals("=")) {
displayField.setText("" + num1);
operator = null;
} else {
operator = command;
displayField.setText("");
}
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
希望这个代码能够帮到你!
阅读全文