java计算器加减乘除
时间: 2023-11-22 17:48:43 浏览: 66
以下是一个使用Java Swing组件编写的简易计算器,可以进行加减乘除运算:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField num1, num2, result;
private JButton add, subtract, multiply, divide;
public Calculator() {
setTitle("Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
num1 = new JTextField();
num2 = new JTextField();
result = new JTextField();
result.setEditable(false);
add = new JButton("+");
subtract = new JButton("-");
multiply = new JButton("*");
divide = new JButton("/");
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
panel.add(new JLabel("Number 1:"));
panel.add(num1);
panel.add(new JLabel("Number 2:"));
panel.add(num2);
panel.add(new JLabel("Result:"));
panel.add(result);
panel.add(add);
panel.add(subtract);
panel.add(multiply);
panel.add(divide);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText()); double r = 0;
if (e.getSource() == add) {
r = n1 + n2;
} else if (e.getSource() == subtract) {
r = n1 - n2;
} else if (e.getSource() == multiply) {
r = n1 * n2;
} else if (e.getSource() == divide) {
r = n1 / n2;
}
result.setText(String.valueOf(r));
}
public static void main(String[] args) {
new Calculator();
}
}
```
阅读全文