6、 编写Example03类,创建一个名为“流式布局”的窗体,设置窗体中的布局管理器为FlowLayout。 创建1个按钮,并为按钮添加点击事件,每点击一次按钮就再生成新的按钮。。
时间: 2024-03-05 17:50:41 浏览: 32
好的,以下是Example03类的代码实现:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example03 extends JFrame implements ActionListener {
private JButton addButton;
private JPanel buttonPanel;
public Example03() {
super("流式布局");
addButton = new JButton("添加按钮");
addButton.addActionListener(this);
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
setContentPane(buttonPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JButton newButton = new JButton("按钮");
buttonPanel.add(newButton);
validate();
}
public static void main(String[] args) {
new Example03();
}
}
```
在代码中,我们创建了一个继承自JFrame的Example03类,它实现了ActionListener接口。在构造方法中,我们创建了一个名为“流式布局”的窗体,并将布局管理器设置为FlowLayout。然后我们创建了一个按钮addButton,并为它添加了点击事件,每点击一次按钮就创建一个新的按钮并添加到窗体中。最后我们将buttonPanel添加到窗体中,并将其设置为窗体的内容面板。
运行程序,点击“添加按钮”按钮,就可以动态地添加新的按钮了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)