java布局之BoxLayout

BoxLayout和FlowLayout有点类似,不过BoxLayout既可以横向排列组件,又设置为纵向排列组件,所以它的功能比FlowLayout强大。它总共有四种约束方式

X_AXIS,Y_AXIS,LINE_AXIS,PAGE_AXIS

X_AXIS:组件从左到右横向排列

Y_AXIS:组件从上到下纵向排列

LINE_AXIS:按照行的方式排列,可以从左到右也可以从右到左

PAGE_AXIS:按照页面的方式排列

/*
 * BoxLayoutDemo.java requires no other files.
 */
 
import java.awt.Component;
import java.awt.Container;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class BoxLayouts extends JFrame{
	
	private JButton btn1 = new JButton("Button1");
	private JButton btn2 = new JButton("Button2");
	private JButton btn3 = new JButton("Button3 what a fine day");
	private JButton btn4 = new JButton("Button4 what a fine da");
	private JButton btn5 = new JButton("Button5 what a fine d");
	private JButton btn6 = new JButton("Button6 what a fines");
	
	BoxLayouts()
	{
		super();
		initComponent();
	}
	private void initComponent()
	{
		Container container = this.getContentPane();
		container.setLayout(new BoxLayout(container,BoxLayout.PAGE_AXIS));
		container.add(btn1);
		container.add(btn2);
		container.add(btn3);
		container.add(btn4);
		container.add(btn5);
		container.add(btn6);
	}
	
	public static void main(String[] args)
	{
		BoxLayouts frame = new BoxLayouts();
		frame.pack();
		frame.setVisible(true);
	}
	
}
图1 Y_AXIS

java布局之BoxLayout_第1张图片

图2 X_AXIS

图3 LINE_AXIS

这里设置了组件的朝向,代码如下所示:

private void initComponent()
	{
		Container container = this.getContentPane();
		container.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		container.setLayout(new BoxLayout(container,BoxLayout.LINE_AXIS));
		container.add(btn1);
		container.add(btn2);
		container.add(btn3);
		container.add(btn4);
		container.add(btn5);
		container.add(btn6);
	}







你可能感兴趣的:(java编程)