FlowLayout(流式布局)
1、FlowLayout布局特征
容器中组件按照设置好的对齐方式(左对齐、居中、右对齐)【默认居中】
从左向右排列,一行排满将换行排列(即组件超过容器宽度后)。
2、流式布局FlowLayout类的常用构造函数和方法
构造函数 |
|
名称 |
用途 |
FlowLayout() 无参 |
构造一个FlowLayout 默认居中对齐,水平和垂直间隙5px |
FlowLayout(int align) |
构造一个FlowLayout,指定对齐方式,水平和垂直间隙5px 对齐方式5参数:(左 中 右 开始 结束*左) 0或FlowLayout.lEFT ,控件左对齐 1或FlowLayout.CENTER ,居中对齐 2或FlowLayout.RIGHT ,右对齐 3或FlowLayout.LEADING,容器方向开始边对应 4或FlowLayout.TRAILING,容器方向结束边对应 其他整数,则为左对齐 |
FlowLayout(int align, int hgap, int vgap) |
构造一个FlowLayout,指定对齐方式和水平垂直间距。 |
方法 |
|
名称 |
用途 |
void setAlignment(int align) |
Set对齐方式ALIGNMENT |
void setHgap(int hgap) |
Set水平间距HGAP |
void setVgap(int vgap) |
Set垂直间距VGAP |
3、FlowLayout 布局 设置例子:
第一步:设置FlowLayout 布局
JFrame fr=new JFrame( ); //创建个叫fr的jframe
FlowLayout flow=new FlowLayout( ); //创建个叫flow的流布局
fr.setLayout(flow); //fr设置为刚刚flow流布局
上面的语句可以简化成:
fr.setLayout(new FlowLayout()); //创建个布局叫fr并设置为流布局
第二布:设置框架fr为组件左对齐的FlowLayout布局
fr.setLayout(newFlowLayout(FlowLayout.LEFT)); //加入对齐参数
第三步:设置框架fr为组件左对齐的FlowLayout布局,并且组件的水平间距为20像素,垂直间距为40像素。
fr.setLayout(new FlowLayout(FlowLayout.LEFT,20,40)); //三设
4、流式布局实例:
//FlowLayoutDemo.java
package flowlayoutdemo;
import javax.swing.*;
import java.awt.*;
public class FlowLayoutDemo extends JFrame {
public FlowLayoutDemo() {
//设置窗体为流式布局,无参默认居中对齐,1=居中,15,15为水平垂直间距15px。
setLayout(newFlowLayout(1,15,15));
//设置窗体中显示的字体样式
setFont(newFont("Helvetica",Font.PLAIN, 14));
//将4个按钮添加到窗体中
getContentPane().add(newJButton("Button 1"));
getContentPane().add(newJButton("Button 2"));
getContentPane().add(newJButton("Button 3"));
getContentPane().add(new JButton("Button4"));
}
public static void main(Stringargs[]) {
FlowLayoutDemo window = newFlowLayoutDemo(); //生成对象window
window.setTitle("流式布局"); //窗口标题
window.pack(); //根据组件自适应窗口大小
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null); //让窗体居中显示
}
}