题目要求:
- 编写类Example01,创建一个名为“流式布局”的窗体。
- 设置窗体中的布局管理器为FlowLayout。
- 创建1个按钮,并为按钮添加点击事件,每点击一次按钮就再生成新的按钮。
分析:
- 设置为流式布局 frama.setLayout(new FlowLayout())
- 对按钮的行为进行监听 button.addActionListener(e->{}) 这里用的是lambda表达式
- 添加新的按钮之后, 要 frame.revalidate(),它是一个方法调用,用于重新验证并更新容器的布局。在 Swing 中,当你向容器中添加或删除组件时,需要通知布局管理器进行重新布局。调用 revalidate() 方法会触发容器的重新验证过程,即通知布局管理器重新计算和调整组件的位置和大小。
代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("流式布局");
frame.setLayout(new FlowLayout()); // 设置为流式布局
frame.setSize(600, 600);
frame.setLocationRelativeTo(null); // 居中显示窗体
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("生成按钮");
frame.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton newButton = new JButton("按钮");
frame.add(newButton);
frame.revalidate();
}
});
frame.setVisible(true);
}
}
运行的结果: