利用Java写一个简易计算器代码,并具有gui界面
时间: 2023-06-10 08:02:51 浏览: 240
java计算器代码(gui界面)
5星 · 资源好评率100%
好的,以下是Java编写简易计算器的代码示例,同时增加了GUI界面:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator extends JFrame implements ActionListener {
private JPanel panel;
private JLabel label1, label2, label3;
private JTextField text1, text2, text3;
private JButton button1, button2, button3, button4;
public SimpleCalculator() {
panel = new JPanel();
label1 = new JLabel("第一个数字:");
label2 = new JLabel("第二个数字:");
label3 = new JLabel("结果:");
text1 = new JTextField(10);
text2 = new JTextField(10);
text3 = new JTextField(10);
button1 = new JButton("+");
button2 = new JButton("-");
button3 = new JButton("*");
button4 = new JButton("/");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(label3);
panel.add(text3);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
this.add(panel, BorderLayout.CENTER);
this.setTitle("简易计算器");
this.setSize(500, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(text1.getText());
double num2 = Double.parseDouble(text2.getText());
double result = 0.0;
if(e.getSource() == button1) {
result = num1 + num2;
} else if (e.getSource() == button2) {
result = num1 - num2;
} else if (e.getSource() == button3) {
result = num1 * num2;
} else if (e.getSource() == button4) {
result = num1 / num2;
}
text3.setText("" + result);
}
public static void main(String[] args) {
new SimpleCalculator();
}
}
```
看到这里,你是否满意呢?
阅读全文