用Java设计和编写一个简易的计算器:实现计算器的界面;实现计算按钮不同的计算功能;显示计算器按钮运算后的结果。
时间: 2024-03-03 10:50:28 浏览: 59
基于Java实现的(GUI)简易计算器【100012745】
5星 · 资源好评率100%
好的,我可以为你提供一下思路:
1. 设计计算器界面:使用Java Swing库中的JFrame、JPanel、JButton等组件来构建一个简单的计算器界面。
2. 实现计算按钮不同的计算功能:定义一个Calculator类,其中包括加、减、乘、除等计算方法,并将其与计算器界面中的计算按钮进行关联。
3. 显示计算器按钮运算后的结果:在计算器界面中增加一个显示结果的文本框,并在每次进行计算后将计算结果显示在该文本框中。
下面是一个简化版的Java代码示例,帮助你更好地理解上述思路:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator {
JFrame frame;
JPanel panel;
JTextField result;
JButton plus, minus, multiply, divide, clear, equals;
double number1, number2, answer;
String operator;
public Calculator() {
frame = new JFrame("Calculator");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(new GridLayout(5, 1));
result = new JTextField();
result.setEditable(false);
panel.add(result);
plus = new JButton("+");
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1 = Double.parseDouble(result.getText());
operator = "+";
result.setText("");
}
});
panel.add(plus);
minus = new JButton("-");
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1 = Double.parseDouble(result.getText());
operator = "-";
result.setText("");
}
});
panel.add(minus);
multiply = new JButton("*");
multiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1 = Double.parseDouble(result.getText());
operator = "*";
result.setText("");
}
});
panel.add(multiply);
divide = new JButton("/");
divide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1 = Double.parseDouble(result.getText());
operator = "/";
result.setText("");
}
});
panel.add(divide);
clear = new JButton("C");
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
result.setText("");
}
});
panel.add(clear);
equals = new JButton("=");
equals.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number2 = Double.parseDouble(result.getText());
switch(operator) {
case "+":
answer = number1 + number2;
break;
case "-":
answer = number1 - number2;
break;
case "*":
answer = number1 * number2;
break;
case "/":
answer = number1 / number2;
break;
}
result.setText(String.valueOf(answer));
}
});
panel.add(equals);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
希望对你有所帮助!
阅读全文