你没有加入clear按钮
时间: 2024-03-26 10:36:13 浏览: 17
非常抱歉,我的回答有误。以下是加入了 Clear 按钮的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGUI extends JFrame implements ActionListener {
private JTextArea textArea;
private JTextField textField;
public MyGUI() {
super("My GUI");
// 创建一个面板
JPanel panel = new JPanel(new FlowLayout());
// 创建一个标签和文本框
JLabel label = new JLabel("输入信息:");
textField = new JTextField(20);
// 创建两个按钮
JButton okButton = new JButton("OK");
JButton clearButton = new JButton("Clear");
// 创建一个文本区域
textArea = new JTextArea(10, 30);
textArea.setEditable(false);
// 将组件添加到面板中
panel.add(label);
panel.add(textField);
panel.add(okButton);
panel.add(clearButton);
// 添加事件监听器
okButton.addActionListener(this);
clearButton.addActionListener(this);
// 将面板和文本区域添加到窗口中
getContentPane().add(panel, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
// 设置窗口属性
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("OK")) {
// 获取文本框中的内容并添加到文本区域中
String text = textField.getText();
textArea.append(text + "\n");
// 清空文本框
textField.setText("");
} else if (e.getActionCommand().equals("Clear")) {
// 清空文本区域和文本框
textArea.setText("");
textField.setText("");
}
}
public static void main(String[] args) {
new MyGUI();
}
}
```
现在,这个程序可以实现输入信息,单击“OK”按钮,在下面的文本区域中显示信息,单击“Clear”按钮将所有数据清除。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)