JAVAGUI俩数相加
时间: 2024-06-13 14:09:13 浏览: 90
两个数相加
以下是一个Java GUI实现俩数相加的例子:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddTwoNumbers extends JFrame implements ActionListener {
private JTextField firstNumberTextField, secondNumberTextField, resultTextField;
private JButton addButton;
public AddTwoNumbers() {
setTitle("Add Two Numbers");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
JLabel firstNumberLabel = new JLabel("First Number:");
firstNumberTextField = new JTextField();
JLabel secondNumberLabel = new JLabel("Second Number:");
secondNumberTextField = new JTextField();
JLabel resultLabel = new JLabel("Result:");
resultTextField = new JTextField();
resultTextField.setEditable(false);
addButton = new JButton("Add");
addButton.addActionListener(this);
panel.add(firstNumberLabel);
panel.add(firstNumberTextField);
panel.add(secondNumberLabel);
panel.add(secondNumberTextField);
panel.add(resultLabel);
panel.add(resultTextField);
panel.add(addButton);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
try {
int firstNumber = Integer.parseInt(firstNumberTextField.getText());
int secondNumber = Integer.parseInt(secondNumberTextField.getText());
int result = firstNumber + secondNumber;
resultTextField.setText(Integer.toString(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter valid numbers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
new AddTwoNumbers();
}
}
```
阅读全文