简易计算器模拟程序java 功能要求:该程序显示GUI用户界面,能实现整数的加、减、乘、除运算。java
时间: 2023-11-10 11:06:23 浏览: 203
好的,我可以帮您实现一个简易计算器模拟程序的Java代码。以下是示例代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField tf1, tf2, tf3;
private JButton add, subtract, multiply, divide;
public Calculator() {
setTitle("Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
tf1 = new JTextField(10);
tf2 = new JTextField(10);
tf3 = new JTextField(10);
add = new JButton("+");
subtract = new JButton("-");
multiply = new JButton("*");
divide = new JButton("/");
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
add(new JLabel("Number 1: "));
add(tf1);
add(new JLabel("Number 2: "));
add(tf2);
add(new JLabel("Result: "));
add(tf3);
add(add);
add(subtract);
add(multiply);
add(divide);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(tf1.getText());
int num2 = Integer.parseInt(tf2.getText());
int result = 0;
if (e.getSource() == add) {
result = num1 + num2;
} else if (e.getSource() == subtract) {
result = num1 - num2;
} else if (e.getSource() == multiply) {
result = num1 * num2;
} else if (e.getSource() == divide) {
result = num1 / num2;
}
tf3.setText(result + "");
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这段代码会创建一个GUI用户界面,包含两个文本框和四个按钮,分别对应加、减、乘、除运算。当用户点击这些按钮时,程序会根据用户输入的两个整数进行相应的运算,并将结果显示在第三个文本框中。
阅读全文