请用【java】帮我写一段代码,要求页面中弹出两个输入框,分别输入两个数字,然后返回两个数字相加的结果
时间: 2024-09-11 07:15:37 浏览: 45
当然可以,这是一个简单的Java Swing GUI程序示例,用于创建两个文本框让用户输入数字,然后计算并显示结果:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddNumbers extends JFrame {
private JTextField textField1, textField2;
private JButton addButton;
private JLabel resultLabel;
public AddNumbers() {
setTitle("Number Addition");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
textField1 = new JTextField();
textField2 = new JTextField();
textField1.setColumns(10);
textField2.setColumns(10);
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int sum = num1 + num2;
resultLabel.setText("Result: " + sum);
}
});
panel.add(new JLabel("Enter first number:"));
panel.add(textField1);
panel.add(new JLabel("Enter second number:"));
panel.add(textField2);
panel.add(addButton);
panel.add(new JLabel());
resultLabel = new JLabel();
panel.add(resultLabel, BorderLayout.SOUTH);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
AddNumbers window = new AddNumbers();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
```
在这个程序中,用户点击"Add"按钮时,会读取两个文本框的内容并计算它们的和,结果显示在`resultLabel`上。
阅读全文