用Java写一个程序,实现如下图形用户界面,点击加法按钮,将两个文本框数值进行加法运算显示在最后一个标签中
时间: 2024-02-29 11:51:43 浏览: 73
很高兴为您解答。以下是使用Java Swing编写的程序代码,实现您所描述的GUI。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorGUI extends JFrame implements ActionListener {
private JLabel label1, label2, resultLabel;
private JTextField textField1, textField2;
private JButton addButton;
public CalculatorGUI() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 150);
setResizable(false);
// create labels
label1 = new JLabel("Number 1:");
label2 = new JLabel("Number 2:");
resultLabel = new JLabel("Result:");
// create text fields
textField1 = new JTextField(10);
textField2 = new JTextField(10);
// create add button
addButton = new JButton("Add");
addButton.addActionListener(this);
// create panels
JPanel panel1 = new JPanel(new GridLayout(3, 2));
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
// add components to panel1
panel1.add(label1);
panel1.add(textField1);
panel1.add(label2);
panel1.add(textField2);
panel1.add(resultLabel);
// add components to panel2
panel2.add(addButton);
// add panels to frame
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
try {
double num1 = Double.parseDouble(textField1.getText());
double num2 = Double.parseDouble(textField2.getText());
double result = num1 + num2;
resultLabel.setText("Result: " + result);
} catch (NumberFormatException ex) {
resultLabel.setText("Result: Invalid input");
}
}
}
public static void main(String[] args) {
CalculatorGUI calculatorGUI = new CalculatorGUI();
calculatorGUI.setVisible(true);
}
}
```
运行该程序后,将会显示一个带有两个文本框和一个加法按钮的GUI界面。用户可以在文本框中输入数字,然后单击“Add”按钮执行加法操作,并将结果显示在标签中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)