BoxLayout用法

来源:互联网 发布:淘宝小卖家月收入统计 编辑:程序博客网 时间:2024/09/15 11:08
package test1;import java.awt.*;import javax.swing.*;public class BoxLayoutTest {    public void init()    {        JPanel jpv=new JPanel();        jpv.setLayout(new BoxLayout(jpv,BoxLayout.X_AXIS));        for(int i=0;i<5;i++)        {            jpv.add(new Button("Button"+i));        }                JPanel jph=new JPanel();        jph.setLayout(new BoxLayout(jph,BoxLayout.Y_AXIS));        for(int j=0;j<5;j++)        {            jph.add(new Button("Button"+j));        }                JFrame jf=new JFrame("BoxLayoiut Test");        jf.add(jpv,"North");        jf.add(jph,"South");        jf.setSize(600,300);        jf.setLocation(100,100);        jf.setVisible(true);    }        public static void main(String[] args)    {        BoxLayoutTest blt=new BoxLayoutTest();        blt.init();    }}

转自:http://blog.csdn.net/zhuche110/article/details/2305491

注意上面的例子用的是Button控件

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

图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);    }

转自:http://www.2cto.com/kf/201401/275555.html

0 0