用Java设计一个图形用户界面,要求按下添加按钮,在多行文本域中显示输入的信息(如姓名,年龄,爱好))
时间: 2024-03-23 09:39:29 浏览: 29
好的,我可以为您提供一个简单的Java图形用户界面,其中包括一个添加按钮和一个多行文本域。您可以在其中输入姓名,年龄和爱好,并按下添加按钮,以将其添加到多行文本域中。
以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUIExample extends JFrame implements ActionListener {
private JTextArea textArea;
private JLabel nameLabel, ageLabel, hobbyLabel;
private JTextField nameField, ageField, hobbyField;
private JButton addButton;
public GUIExample() {
// 设置窗口标题
setTitle("添加用户信息");
// 创建标签和文本框
nameLabel = new JLabel("姓名:");
nameField = new JTextField(10);
ageLabel = new JLabel("年龄:");
ageField = new JTextField(10);
hobbyLabel = new JLabel("爱好:");
hobbyField = new JTextField(10);
// 创建添加按钮
addButton = new JButton("添加");
addButton.addActionListener(this);
// 创建多行文本域
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
// 将组件添加到窗口中
JPanel panel = new JPanel();
panel.add(nameLabel);
panel.add(nameField);
panel.add(ageLabel);
panel.add(ageField);
panel.add(hobbyLabel);
panel.add(hobbyField);
panel.add(addButton);
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.NORTH);
contentPane.add(new JScrollPane(textArea), BorderLayout.CENTER);
// 设置窗口大小并显示
setSize(400, 300);
setVisible(true);
}
// 处理添加按钮的点击事件
public void actionPerformed(ActionEvent e) {
// 获取用户输入的姓名、年龄和爱好
String name = nameField.getText();
String age = ageField.getText();
String hobby = hobbyField.getText();
// 将用户输入的信息添加到多行文本域中
textArea.append("姓名: " + name + "\n");
textArea.append("年龄: " + age + "\n");
textArea.append("爱好: " + hobby + "\n\n");
// 清空文本框
nameField.setText("");
ageField.setText("");
hobbyField.setText("");
}
public static void main(String[] args) {
new GUIExample();
}
}
```
您可以将此代码复制到您的Java IDE中,并运行它以查看结果。当您按下添加按钮并在文本框中输入信息时,您应该能够在多行文本域中看到该信息。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)