1、JavaSwing 布局管理器——FlowLayout(流式布局)

概述

官方JavaDocsApi: https://docs.oracle.com/javase/8/docs/api/java/awt/FlowLayout.html

 

FlowLayout,流式布局管理器。按水平方向依次排列放置组件,排满一行,换下一行继续排列。排列方向(左到右 或 右到左)取决于容器的componentOrientation属性(该属性属于Component),它可能的值如下:

  • ComponentOrientation.LEFT_TO_RIGHT(默认)
  • ComponentOrientation.RIGHT_TO_LEFT

同一行(水平方向)的组件的对齐方式由 FlowLayout 的align属性确定,它可能的值如下:

FlowLayout.LEFT

左对齐

FlowLayout.CENTER

居中对齐(默认)

FlowLayout.RIGHT

右对齐

FlowLayout.LEADING

与容器方向的开始边对齐,例如,对于从左到右的方向,则与左边对齐

FlowLayout.TRAILING

与容器方向的结束边对齐,例如,对于从左到右的方向,则与右边对齐。

 

FlowLayout的 构造方法:

FlowLayout()

 

// 默认 居中对齐的,水平和垂直间隙是 5 个单位

 

FlowLayout(int align)

// 指定对齐方式,默认的水平和垂直间隙是 5 个单位

FlowLayout(int align, int hgap, int vgap)

 

// 指定对其方式,水平 和 竖直 间隙

案例

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestFlowLayout {

	public static void main(String[] args) {

		//创建顶层窗口
		JFrame jf = new JFrame();
		jf.setSize(400,300);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setLocationRelativeTo(null);
		
		//创建中间容器 设置布局
		//JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));  //右对齐
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,20,20));  //水平和竖直间隙
		//创建按钮
		JButton btn1 = new JButton("按钮1");
		JButton btn2 = new JButton("按钮2");
		JButton btn3 = new JButton("按钮3");
		JButton btn4 = new JButton("按钮4");
		JButton btn5 = new JButton("按钮5");
		JButton btn6 = new JButton("按钮6");
		JButton btn7 = new JButton("按钮7");
		//将按钮添加到面板中
		panel.add(btn1);
		panel.add(btn2);
		panel.add(btn3);
		panel.add(btn4);
		panel.add(btn5);
		panel.add(btn6);
		panel.add(btn7);
		
		//将中间容器面板添加到窗口中
		jf.setContentPane(panel);
		
		//显示
		jf.setVisible(true);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_43629083/article/details/109017457