Java简易计算器界面以及功能设计
时间: 2023-09-10 18:15:32 浏览: 112
下面是一个简单的Java计算器程序,具有基本的计算功能和一个简单的图形用户界面:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private JButton clear, add, subtract, multiply, divide, equals;
private JButton[] digits;
private double currentNumber = 0;
private String currentOperation = "";
public Calculator() {
super("Calculator");
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel(new FlowLayout());
display = new JTextField(10);
panel1.add(display);
JPanel panel2 = new JPanel(new GridLayout(4, 3));
digits = new JButton[10];
for (int i = 0; i < 10; i++) {
digits[i] = new JButton("" + i);
digits[i].addActionListener(this);
panel2.add(digits[i]);
}
clear = new JButton("C");
clear.addActionListener(this);
panel2.add(clear);
add = new JButton("+");
add.addActionListener(this);
panel2.add(add);
subtract = new JButton("-");
subtract.addActionListener(this);
panel2.add(subtract);
multiply = new JButton("*");
multiply.addActionListener(this);
panel2.add(multiply);
divide = new JButton("/");
divide.addActionListener(this);
panel2.add(divide);
equals = new JButton("=");
equals.addActionListener(this);
panel2.add(equals);
setLayout(new BorderLayout());
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("C")) {
currentNumber = 0;
display.setText("");
} else if (action.equals("+")) {
currentOperation = "+";
currentNumber = Double.parseDouble(display.getText());
display.setText("");
} else if (action.equals("-")) {
currentOperation = "-";
currentNumber = Double.parseDouble(display.getText());
display.setText("");
} else if (action.equals("*")) {
currentOperation = "*";
currentNumber = Double.parseDouble(display.getText());
display.setText("");
} else if (action.equals("/")) {
currentOperation = "/";
currentNumber = Double.parseDouble(display.getText());
display.setText("");
} else if (action.equals("=")) {
double secondNumber = Double.parseDouble(display.getText());
double result = 0;
if (currentOperation.equals("+")) {
result = currentNumber + secondNumber;
} else if (currentOperation.equals("-")) {
result = currentNumber - secondNumber;
} else if (currentOperation.equals("*")) {
result = currentNumber * secondNumber;
} else if (currentOperation.equals("/")) {
result = currentNumber / secondNumber;
}
currentNumber = result;
display.setText("" + result);
} else {
display.setText(display.getText() + action);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
}
```
该程序使用JFrame和JPanel创建了一个简单的图形用户界面。JPanel使用GridLayout来放置数字和操作按钮,而JTextField用于显示当前计算结果。
当用户按下数字按钮时,该数字将显示在JTextField中。当用户按下操作按钮时,程序将保存当前数字并等待下一个数字。当用户按下等号按钮时,程序将计算结果并在JTextField中显示。
该程序非常简单,但它可以帮助您了解如何以编程方式创建基本的图形用户界面,并使用Java进行简单的数学计算。
阅读全文