请用java GUI编写一个运算器应用程序。要求实现运算器中常用的功能(+,-,*,、)。
时间: 2024-03-20 16:44:31 浏览: 59
好的,我可以为您提供一个简单的Java GUI运算器代码实现。请注意,这只是一个基本的示例,您可以根据自己的需求进行修改和改进。
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel label1, label2, label3;
private JTextField text1, text2, text3;
private JButton buttonAdd, buttonSub, buttonMul, buttonDiv;
public Calculator() {
super("Calculator");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
initComponents();
setVisible(true);
}
private void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.WHITE);
label1 = new JLabel("Number 1:");
label1.setBounds(50, 50, 100, 30);
panel.add(label1);
text1 = new JTextField();
text1.setBounds(160, 50, 150, 30);
panel.add(text1);
label2 = new JLabel("Number 2:");
label2.setBounds(50, 100, 100, 30);
panel.add(label2);
text2 = new JTextField();
text2.setBounds(160, 100, 150, 30);
panel.add(text2);
buttonAdd = new JButton("+");
buttonAdd.setBounds(50, 150, 50, 50);
buttonAdd.setFont(new Font("Arial", Font.BOLD, 20));
buttonAdd.addActionListener(this);
panel.add(buttonAdd);
buttonSub = new JButton("-");
buttonSub.setBounds(120, 150, 50, 50);
buttonSub.setFont(new Font("Arial", Font.BOLD, 20));
buttonSub.addActionListener(this);
panel.add(buttonSub);
buttonMul = new JButton("*");
buttonMul.setBounds(190, 150, 50, 50);
buttonMul.setFont(new Font("Arial", Font.BOLD, 20));
buttonMul.addActionListener(this);
panel.add(buttonMul);
buttonDiv = new JButton("/");
buttonDiv.setBounds(260, 150, 50, 50);
buttonDiv.setFont(new Font("Arial", Font.BOLD, 20));
buttonDiv.addActionListener(this);
panel.add(buttonDiv);
label3 = new JLabel("Result:");
label3.setBounds(50, 220, 100, 30);
panel.add(label3);
text3 = new JTextField();
text3.setBounds(160, 220, 150, 30);
text3.setEditable(false);
panel.add(text3);
add(panel);
}
@Override
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(text1.getText());
double num2 = Double.parseDouble(text2.getText());
if(e.getSource() == buttonAdd) {
double result = num1 + num2;
text3.setText(Double.toString(result));
}
else if(e.getSource() == buttonSub) {
double result = num1 - num2;
text3.setText(Double.toString(result));
}
else if(e.getSource() == buttonMul) {
double result = num1 * num2;
text3.setText(Double.toString(result));
}
else if(e.getSource() == buttonDiv) {
double result = num1 / num2;
text3.setText(Double.toString(result));
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序创建了一个简单的GUI界面,包含两个文本框和四个按钮(加、减、乘、除),当用户点击按钮时,程序将读取文本框中的数字,执行相应的运算,并将结果显示在另一个文本框中。
阅读全文