【Java Swing探索之路系列】之三:Java Swing布局管理器组件

作者:郭嘉

邮箱:[email protected]

博客:http://blog.csdn.net/allenwells

github:https://github.com/AllenWell

一 BorderLayout

BorderLayout是一种简单的布局策略,可以将其看作一个组件。它把容器分为东、南、西、北、中5个区域,每个组件将占据某个区域。而

这5个区域分别被命名为NORTH, WEST, EAST, CENTER, SOUTH,它们都被定义为静态

常量.静态常量可以直接引用,如下所示:

  • Public static final String NORTH = “North” 整个内容面板的北边
  • Public static final String WEST = “West” 整个内容面板的西边
  • Public static final String EAST = “EasT” 整个内容面板的东边
  • Public static final Sning CENTER = “Center” 整个内容面板的中间
  • Public static final String SOUTH = “South” 整个内容面板的南边

举例1

如何使用BorderLayout布局管理器将组件进行布局。

import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo1
{
    static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {

         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("生活");
         JButton b2=new JButton("工作");
         JButton b3=new JButton("睡觉");
         JButton b4=new JButton("购物");
         JButton b5=new JButton("饮食");
         BorderLayout lay=new BorderLayout();//创建一个布局管理器对象,将中间容器设置为此布局管理
         jf.setLayout(lay);
         contentPane.add(b1,"North");//将五个普通按钮组件分别按照东、南、西、北、中五个方位添加到中间容器中
         contentPane.add(b2,"South");
         contentPane.add(b3,"East");
         contentPane.add(b4,"West");
         contentPane.add(b5,"Center");
    }
}

运行结果如下图所示:

举例2

将五个内容面板添加到于顶层容器相关连的内容面板中的五个不同方向,而本身这五个内容面板中也分别包含了位于五个不同方向的按钮组件。

//这段代码主要是为读者展示如何将五个内容面板添加到于顶层容器相关连的内容面板中的五个不同方向,而本身这五个内容面板中也分别包含了位于五个不同方向的按钮组件
import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo2
{
static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {
         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("港币");//创建了二十五个普通按钮组件
         JButton b2=new JButton("人民币");
         JButton b3=new JButton("美元");
         JButton b4=new JButton("欧元");
         JButton b5=new JButton("英镑");
         JButton b6=new JButton("主板");
         JButton b7=new JButton("内存");
         JButton b8=new JButton("硬盘");
         JButton b9=new JButton("显示器");
         JButton b10=new JButton("鼠标");
         JButton b11=new JButton("大米");
         JButton b12=new JButton("蔬菜");
         JButton b13=new JButton("稻子");
         JButton b14=new JButton("猪肉");
         JButton b15=new JButton("牛肉");
         JButton b16=new JButton("面包");
         JButton b17=new JButton("蛋糕");
         JButton b18=new JButton("巧克力");
         JButton b19=new JButton("奶酪");
         JButton b20=new JButton("苹果派");
         JButton b21=new JButton("笔记本");
         JButton b22=new JButton("电话");
         JButton b23=new JButton("办公桌");
         JButton b24=new JButton("钢笔");
         JButton b25=new JButton("文件夹");
         jf.setLayout(new BorderLayout());
         JPanel p1=new JPanel();//创建了五个中间容器,并且将它们的布局管理器都设置成BorderLayout方式。
         JPanel p2=new JPanel();
         JPanel p3=new JPanel();
         JPanel p4=new JPanel();
         JPanel p5=new JPanel();
         p1.setLayout(new BorderLayout());
         p2.setLayout(new BorderLayout());
         p3.setLayout(new BorderLayout());
         p4.setLayout(new BorderLayout());
         p5.setLayout(new BorderLayout());
         contentPane.add(p1,"North");//将五个中间容器对象分别加入到上层中间容器中,并且是按照BorderLayout的方式进行布局
         contentPane.add(p2,"South");
         contentPane.add(p3,"East");
         contentPane.add(p4,"West");
         contentPane.add(p5,"Center");
         p1.add(b1,"North");///将从第一个到第五个普通按钮组件按照BorderLayout方式布局到p1中间容器中
         p1.add(b2,"West");
         p1.add(b3,"South");
         p1.add(b4,"East");
         p1.add(b5,"Center");
         p2.add(b6,"North");//将从第六个到第十个普通按钮组件按照BorderLayout方式布局到p2中间容器中
         p2.add(b7,"West");
         p2.add(b8,"South");
         p2.add(b9,"East");
         p2.add(b10,"Center");
         p3.add(b11,"North");//将从第十一个到第十五个普通按钮组件按照BorderLayout方式布局到p3中间容器中
         p3.add(b12,"West");
         p3.add(b13,"South");
         p3.add(b14,"East");
         p3.add(b15,"Center");
         p4.add(b16,"North");//将从第十六个到第二十个普通按钮组件按照BorderLayout方式布局到p4中间容器中
         p4.add(b17,"West");
         p4.add(b18,"South");
         p4.add(b19,"East");
         p4.add(b20,"Center");
         p5.add(b21,"North");//将从第二十一个到第二十五个普通按钮组件按照BorderLayout方式布局到p5中间容器中
         p5.add(b22,"West");
         p5.add(b23,"South");
         p5.add(b24,"East");
         p5.add(b25,"Center");
         }
}

运行结果如下图所示:

二 FlowLayout

FlowLayout按照组件加入的先后顺序从左到右排列,一行徘满了,再换下一行,然后继续从左到右排列,每一行的组件都是居中排列的。

举例1

FlowLayout布局管理器的使用方法

//这段代码主要是为读者展示FlowLayout布局管理器的使用方法
import javax.swing.*;
import java.awt.*;
public class FlowLayoutDemo1
{
static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {
         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("港币");
         JButton b2=new JButton("人民币");
         JButton b3=new JButton("美元");
         JButton b4=new JButton("欧元");
         JButton b5=new JButton("英镑");
         contentPane.setLayout(new FlowLayout());//将中间容器的布局管理器设置为FlowLayout
         contentPane.add(b1); //将五个按钮分别按照FlowLayout布局管理器方式添加到中间容器中
         contentPane.add(b2);
         contentPane.add(b3);
         contentPane.add(b4);
         contentPane.add(b5);
         jf.pack();
        }
}

运行效果如下图所示:

举例2

将FlowLayout布局管理器同顶层容器关联,然后再在其中添加五个布局管理器的内容面板,而这个内容面板,每一个内容面板添加五个组件,每一个内容面板是按照BorderLayout布局管理方式排列组件。

import javax.swing.*;
import java.awt.*;
public class FlowLayoutDemo2
{
static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {
         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("港币");//创建了二十五个普通按钮组件
         JButton b2=new JButton("人民币");
         JButton b3=new JButton("美元");
         JButton b4=new JButton("欧元");
         JButton b5=new JButton("英镑");
         JButton b6=new JButton("主板");
         JButton b7=new JButton("内存");
         JButton b8=new JButton("硬盘");
         JButton b9=new JButton("显示器");
         JButton b10=new JButton("鼠标");
         JButton b11=new JButton("大米");
         JButton b12=new JButton("蔬菜");
         JButton b13=new JButton("稻子");
         JButton b14=new JButton("猪肉");
         JButton b15=new JButton("牛肉");
         JButton b16=new JButton("面包");
         JButton b17=new JButton("蛋糕");
         JButton b18=new JButton("巧克力");
         JButton b19=new JButton("奶酪");
         JButton b20=new JButton("苹果派");
         JButton b21=new JButton("笔记本");
         JButton b22=new JButton("电话");
         JButton b23=new JButton("办公桌");
         JButton b24=new JButton("钢笔");
         JButton b25=new JButton("文件夹");
         contentpane.setLayout(new FlowLayout());//将中间容器的布局管理器设为FlowLayout
         JPanel p1=new JPanel();//创建五个中间容器,并且将每个中间容器的布局管理器设置为BorderLayout
         JPanel p2=new JPanel();
         JPanel p3=new JPanel();
         JPanel p4=new JPanel();
         JPanel p5=new JPanel();
         p1.setLayout(new BorderLayout());
         p2.setLayout(new BorderLayout());
         p3.setLayout(new BorderLayout());
         p4.setLayout(new BorderLayout());
         p5.setLayout(new BorderLayout());
         contentPane.add(p1); //将五个中间容器添加到上层中间容器
         contentPane.add(p2);
         contentPane.add(p3);
         contentPane.add(p4);
         contentPane.add(p5);
         p1.add(b1,"North");//将第一个到第五个普通按钮添加到p1中
         p1.add(b2,"West");
         p1.add(b3,"South");
         p1.add(b4,"East");
         p1.add(b5,"Center");
         p2.add(b6,"North");//将第六个到第十个普通按钮添加到p2中
         p2.add(b7,"West");
         p2.add(b8,"South");
         p2.add(b9,"East");
         p2.add(b10,"Center");
         p3.add(b11,"North");//将第十个到第十五个普通按钮添加p3中
         p3.add(b12,"West");
         p3.add(b13,"South");
         p3.add(b14,"East");
         p3.add(b15,"Center");
         p4.add(b16,"North");//将第十六个到第二十个普通按钮添加到p4中
         p4.add(b17,"West");
         p4.add(b18,"South");
         p4.add(b19,"East");
         p4.add(b20,"Center");
         p5.add(b21,"North");//将第二十一个到第二十五个普通按钮添加到p5中
         p5.add(b22,"West");
         p5.add(b23,"South");
         p5.add(b24,"East");
         p5.add(b25,"Center");
         jf.pack();
       }
}

运行效果如下图所示:

三 GridLayout

GridLayout将整个空间划分成若干行乘若干列的网络区域,组件就放于这些小区域内。

举例1

使用GridLayout布局管理器,在程序中将九个普通按钮组件按照此布局管理器放置在内容面板中。

import javax.swing.*;
import java.awt.*;
public class test5
{
    static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {
         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("港币");
         JButton b2=new JButton("人民币");
         JButton b3=new JButton("美元");
         JButton b4=new JButton("欧元");
         JButton b5=new JButton("英镑");
         JButton b6=new JButton("主板");
         JButton b7=new JButton("内存");
         JButton b8=new JButton("硬盘");
         JButton b9=new JButton("显示器");

         GridLayout gird=new GridLayout(3,3); //创建一个 GridLayout布局管理器对象,将之行数设为3,列数设为3,并且将之作为中间容器的布局管理器
         contentPane.setLayout(gird);

         contentPane.add(b1); //将九个普通按钮组件一一添加到中间容器中
         contentPane.add(b2);
         contentPane.add(b3);
         contentPane.add(b4);
         contentPane.add(b5);
         contentPane.add(b6);
         contentPane.add(b7);
         contentPane.add(b8);
         contentPane.add(b9);
         jf.pack();
      }
}

运行效果如下图所示:

举例2

用GirdLayout布局管理器与顶层窗口关联,在这个布局管理器中添加FlowLayout布局管理器和BorderLayout布局管理器,最后,在这些布局管理器中添加控件。

import javax.swing.*;
import java.awt.*;
public class test6
{
    static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {

         JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
         JButton b1=new JButton("港币");//创建了二十五个普通按钮组件
         JButton b2=new JButton("人民币");
         JButton b3=new JButton("美元");
         JButton b4=new JButton("欧元");
         JButton b5=new JButton("英镑");
         JButton b6=new JButton("主板");
         JButton b7=new JButton("内存");
         JButton b8=new JButton("硬盘");
         JButton b9=new JButton("显示器");
         JButton b10=new JButton("鼠标");
         JButton b11=new JButton("大米");
         JButton b12=new JButton("蔬菜");
         JButton b13=new JButton("稻子");
         JButton b14=new JButton("猪肉");
         JButton b15=new JButton("牛肉");
         JButton b16=new JButton("面包");
         JButton b17=new JButton("蛋糕");
         JButton b18=new JButton("巧克力");
         JButton b19=new JButton("奶酪");
         JButton b20=new JButton("苹果派");
         JButton b21=new JButton("笔记本");
         JButton b22=new JButton("电话");
         JButton b23=new JButton("办公桌");
         JButton b24=new JButton("钢笔");
         JButton b25=new JButton("文件夹");
         GridLayout gird=new GridLayout(3,3);
         jf.setLayout(gird);
         JPanel p1=new JPanel();//创建五个中间容器,并且将第一个和第二个,第四个、第五个中间容器的布局方式设置为BorderLayout,而第三个设置为FlowLayout
         JPanel p2=new JPanel();
         JPanel p3=new JPanel();
         JPanel p4=new JPanel();
         JPanel p5=new JPanel();
         p1.setLayout(new BorderLayout());
         p2.setLayout(new BorderLayout());
         p3.setLayout(new FlowLayout());
         p4.setLayout(new BorderLayout());
         p5.setLayout(new BorderLayout());
         contentPane.add(p1); //将五个中间容器添加到外层中间容器中
         contentPane.add(p2);
         contentPane.add(p3);
         contentPane.add(p4);
         contentPane.add(p5);
         p1.add(b1,"North");//将第一个组件到第五个组件添加到p1
         p1.add(b2,"West");
         p1.add(b3,"South");
         p1.add(b4,"East");
         p1.add(b5,"Center");
         p2.add(b6,"North");//将第六个组件到第十个组件添加到p2
         p2.add(b7,"West");
         p2.add(b8,"South");
         p2.add(b9,"East");
         p2.add(b10,"Center");
         p3.add(b11); //将第十一个组件到第十五个组件添加到p3
         p3.add(b12);
         p3.add(b13);
         p3.add(b14);
         p3.add(b15);
         p4.add(b16,"North");//将第十六个组件到第二十个组件添加到p4
         p4.add(b17,"West");
         p4.add(b18,"South");
         p4.add(b19,"East");
         p4.add(b20,"Center");
         p5.add(b21,"North");//创建第二十一个组件到第二十五个组件添加到 p5
         p5.add(b22,"West");
         p5.add(b23,"South");
         p5.add(b24,"East");
         p5.add(b25,"Center");
         jf.pack();
      }
}

运行效果如下图所示:

四 GridBagLayout

GridBagLayout也是对区域进行网络划分,不同之处在于,组件可以占据一个网格,也可以占据几个网格。

举例1

使用GridBagLayout布局管理器布局方式来排列内容面板中的组件

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test7 extends JPanel//此处类继承了JPanel类
{
    static final int WIDTH=300;
    static final int HEIGHT=150;
    JFrame loginframe;
    public void add(Component c,GridBagConstraints constraints,int x,int y,int w,int h)
    {//此方法用来添加控件到容器中
        constraints.gridx=x;
        constraints.gridy=y;
        constraints.gridwidth=w;
        constraints.gridheight=h;
        add(c,constraints);
}
    test7()
    {
        loginframe=new JFrame("信息管理系统"); //设置顶层容器
        loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置其顶层容器的关闭性
        GridBagLayout lay=new GridBagLayout();//创建网格组布局方式对象
        setLayout(lay);
        loginframe.add(this, BorderLayout.WEST);
        loginframe.setSize(WIDTH,HEIGHT);
        Toolkit kit=Toolkit.getDefaultToolkit();//设置顶层容器框架为居中
        Dimension screenSize=kit.getScreenSize();
        int width=screenSize.width;
        int height=screenSize.height;
        int x=(width-WIDTH)/2;
        int y=(height-HEIGHT)/2;
        loginframe.setLocation(x,y);
        JButton ok=new JButton("确认");
        JButton cancel=new JButton("放弃");
        JLabel title=new JLabel("布局管理器测试窗口");
        JLabel name=new JLabel("用户名");
        JLabel password=new JLabel("密 码");
        final JTextField nameinput=new JTextField(15);
        final JTextField passwordinput=new JTextField(15);
        GridBagConstraints constraints=new GridBagConstraints();
        constraints.fill=GridBagConstraints.NONE;
        constraints.anchor=GridBagConstraints.EAST;
        constraints.weightx=3;
        constraints.weighty=4;
        add(title,constraints,0,0,4,1); //使用网格组布局添加控件
        add(name,constraints,0,1,1,1);
        add(password,constraints,0,2,1,1);
        add(nameinput,constraints,2,1,1,1);
        add(passwordinput,constraints,2,2,1,1);
        add(ok,constraints,0,3,1,1);
        add(cancel,constraints,2,3,1,1);
        loginframe.setResizable(false);
        loginframe.setVisible(true);
    }
}
public class test7
{
    public static void main(String[] args)
    {
        login log=new login();
}
 }

运行效果如下图所示:

五 CardLayout

CardLayout将容器中的每一个组件当做一个卡片,每次仅有一个卡片可见,卡片之间可以来回切换。

举例

使用CardLayout布局管理器针对内容面板中的组件进行布局。

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class test8 extends JFrame
{
    private JPanel pane = null; // 主要的JPanel,该JPanel的布局管理将被设置成CardLayout
    private JPanel p = null; // 放按钮的JPanel
    private CardLayout card = null; // CardLayout布局管理器
    private JButton button_1 = null; // 上一步
    private JButton button_2 = null; // 下一步
    private JButton b_1 = null, b_2 = null, b_3 = null; // 三个可直接翻转到JPanel组件的按钮
    private JPanel p_1 = null, p_2 = null, p_3 = null; // 要切换的三个JPanel
    public test8()
{
        super("CardLayout Test");
        try {
            // 将LookAndFeel设置成Windows样式
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
           }
catch (Exception ex)
{
            ex.printStackTrace();
           }
        card = new CardLayout(5, 5); //创建一个具有指定的水平和垂直间隙的新卡片布局
        pane = new JPanel(card); // JPanel的布局管理将被设置成CardLayout
        p = new JPanel(); // 构造放按钮的JPanel
        button_1 = new JButton("< 上一步");
        button_2 = new JButton("下一步 >");
        b_1 = new JButton("1");
        b_2 = new JButton("2");
        b_3 = new JButton("3");
        b_1.setMargin(new Insets(2,2,2,2));
        b_2.setMargin(new Insets(2,2,2,2));
        b_3.setMargin(new Insets(2,2,2,2));
        p.add(button_1);
        p.add(b_1);
        p.add(b_2);
        p.add(b_3);
        p.add(button_2);
        p_1 = new JPanel();
        p_2 = new JPanel();
        p_3 = new JPanel();
        p_1.setBackground(Color.RED);
        p_2.setBackground(Color.BLUE);
        p_3.setBackground(Color.GREEN);
        p_1.add(new JLabel("JPanel_1"));
        p_2.add(new JLabel("JPanel_2"));
        p_3.add(new JLabel("JPanel_3"));
        pane.add(p_1, "p1");
        pane.add(p_2, "p2");
        pane.add(p_3, "p3");
         //下面是翻转到卡片布局的某个组件的动作事件处理,当单击某个普通按钮组件,就会触发出现下一个组件
        button_1.addActionListener(new ActionListener()
{
/// 上一步的按钮动作
            public void actionPerformed(ActionEvent e) {
                card.previous(pane);
            }
        });
        button_2.addActionListener(new ActionListener()
{
// 下一步的按钮动作
            public void actionPerformed(ActionEvent e) {
                card.next(pane);
            }
        });
        b_1.addActionListener(new ActionListener()
{
// 直接翻转到p_1
            public void actionPerformed(ActionEvent e) {
                card.show(pane, "p1");
            }
        });
        b_2.addActionListener(new ActionListener()
{
// 直接翻转到p_2
            public void actionPerformed(ActionEvent e) {
                card.show(pane, "p2");
            }
        });
        b_3.addActionListener(new ActionListener()
{
// 直接翻转到p_3
            public void actionPerformed(ActionEvent e) {
                card.show(pane, "p3");
            }
        });
        this.getContentPane().add(pane);
        this.getContentPane().add(p, BorderLayout.SOUTH);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 200);
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new test8();
    }

}

运行效果如下图所示:

六 BoxLayout

BoxLayout是箱式布局,它可以创建水平箱和垂直箱两种箱子。

举例

使用BoxLayout 布局管理器针对组件进行布局。

import javax.swing.*;
import java.awt.*;
public class test9
{

    public static void main(String[] args)
    {
        BoxLayoutFrame frame1=new BoxLayoutFrame();
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setVisible(true);
    }
}
class BoxLayoutFrame extends JFrame
{
    private static final int WIDTH=300;
    private static final int HEIGHT=200;
    public BoxLayoutFrame()
    {

        setTitle("测试箱式布局管理器");//设置顶层容器名称、大小
        setSize(WIDTH,HEIGHT);
        Container con=getContentPane();//创建一个中间容器
        JLabel label1=new JLabel(" 姓名:");//创建标签组件、文本框组件
        JTextField textField1=new JTextField(10);
        textField1.setMaximumSize(textField1.getPreferredSize());
        Box hbox1=Box.createHorizontalBox();//创建一个水平箱子
        hbox1.add(label1); //在水平箱子上添加一个标签组件,并且创建一个不可见的、20个单位的组件。在这之后再添加一个文本框组件
        hbox1.add(Box.createHorizontalStrut(20));
        hbox1.add(textField1);
        JLabel label2=new JLabel(" 密码:");//创建标签组件、文本框组件
        JTextField textField2=new JTextField(10);
        textField2.setMaximumSize(textField2.getPreferredSize());
        Box hbox2=Box.createHorizontalBox();//创建一个水平箱子
        hbox2.add(label2); //在水平箱子上添加一个标签组件,并且创建一个不可见的、20个单位的组件。在这之后再添加一个文本框组件
        hbox2.add(Box.createHorizontalStrut(20));
        hbox2.add(textField2);
        JButton button1=new JButton("确定");//创建两个普通按钮组件,并且创建一个水平箱子,将两个按钮添加到箱子中
        JButton button2=new JButton("取消");
        Box hbox3=Box.createHorizontalBox();
        hbox3.add(button1);
        hbox3.add(button2);
        Box vbox=Box.createVerticalBox();//创建一个垂直箱子,这个箱子将两个水平箱子添加到其中,创建一个横向 glue 组件。
        vbox.add(hbox1);
        vbox.add(hbox2);
        vbox.add(Box.createVerticalGlue());
        vbox.add(hbox3);
        con.add(vbox,BorderLayout.CENTER); // 将垂直箱子添加到BorderLayout布局管理器中的中间位置
    }
}

运行效果如下图所示:

七 SpringLayout

SpringLayout是通过定义组件边沿距离来实现布局的,边界之间的距离是使用Spring对象来表示的,每一个Spring对象具有4个属性值,如下所示:

  • mmimum
  • maximum
  • prefemed
  • value:表示的是真实的值。

在这个布局管理器中,涉及到如下几个常量:

  • EAST:指定组件的边界拒形的右边.
  • NORTH:指定组件的边界拒形的顶边
  • SOUTH:指定组件的边界;,形的底边.
  • WEST:指定组件的边界矩形的左边.

举例

使用SpringLayout布局管理器为组件进行布局

import javax.swing.*;
import java.awt.*;
//产生不同的箱子布局管理器对象,每个对象放置不同的控件
public class test10
{
    static final int WIDTH=300;
    static final int HEIGHT=200;
    public static void main(String[] args)
    {
     JFrame jf=new JFrame("测试程序");
         jf.setSize(WIDTH,HEIGHT);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setVisible(true);
         JPanel contentPane=new JPanel();
         jf.setContentPane(contentPane);
        JButton b1=new JButton("测试程序模块1");//创建了两个普通按钮组件、一个标签组件,将它们添加到中间容器中
        JButton b2=new JButton("测试程序模块2");
        JLabel l=new JLabel("测试程序");
        contentPane.add(l);
        contentPane.add(b2);
        contentPane.add(b1);
        // 创建一个 SpringLayout布局管理器,并且将之作为中间容器的布局方式
        SpringLayout lay=new SpringLayout();
        contentPane.setLayout(lay);
        //针对每个组件设置其与边界的距离
        lay.putConstraint(SpringLayout.NORTH,l, 5,SpringLayout.NORTH,contentPane);
        lay.putConstraint(SpringLayout.WEST,l, 85,SpringLayout.WEST,contentPane);
        lay.putConstraint(SpringLayout.EAST,l, 85,SpringLayout.EAST,contentPane);
        lay.putConstraint(SpringLayout.NORTH,b1, 55,SpringLayout.NORTH,contentPane);
        lay.putConstraint(SpringLayout.WEST,b1, 5,SpringLayout.WEST,contentPane);
        lay.putConstraint(SpringLayout.EAST,b1, 25,SpringLayout.EAST,contentPane);
        lay.putConstraint(SpringLayout.NORTH,b2, 105,SpringLayout.NORTH,contentPane);
        lay.putConstraint(SpringLayout.WEST,b2, 5,SpringLayout.WEST,contentPane);
        lay.putConstraint(SpringLayout.EAST,b2, 25,SpringLayout.EAST,contentPane);
    }
}

运行效果如下图所示:

八 GroupLayout

GroupLayout是以组为单位来管理布局的,把多个组件划分到不容的组,再根据各个组相对于水平轴和垂直轴的排列方式来进行组的管理。

举例

使用GroupLayout布局管理器进行布局。

import java.awt.Container;
import java.awt.HeadlessException;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class test11 extends JFrame
{
private static final long serialVersionUID = 1L;
public test11() throws HeadlessException
{
   Container c = getContentPane();//创建一个中间容器,并且创建一个GroupLayout布局管理器对象
   GroupLayout layout = new GroupLayout(c);
   JButton b1 = new JButton("按钮 1");//创建两个普通按钮组件、文本框组件
   JButton b2 = new JButton("按钮 2");
   JTextField text = new JTextField("文本");
   GroupLayout.SequentialGroup hsg = layout.createSequentialGroup();//创建一个hsg组,将两个按钮一个一个的添加到组里面
   hsg.addComponent(b1);
   hsg.addComponent(b2);
   GroupLayout.ParallelGroup hpg =
   layout.createParallelGroup(GroupLayout.Alignment.CENTER); //创建一个hpg组,将文本框组件和上面的那个组添加到其中,并且居中排列
   hpg.addComponent(text).addGroup(hsg);
   layout.setHorizontalGroup(hpg); //沿水平线来确定hpg组中两个按钮组件的位置
   GroupLayout.ParallelGroup vpg = layout.createParallelGroup();//创建一个vpg组,按照水平线来排列两个按钮组件的位置
   vpg.addComponent(b1);
   vpg.addComponent(b2);
   GroupLayout.SequentialGroup vsg = layout.createSequentialGroup();// 将文本框组件和前面的容纳两个按钮组件的组同时添加到vsg组中
   vsg.addComponent(text).addGroup(vpg);
   layout.setVerticalGroup(vsg); //沿垂直线来确定vsg中vpg和文本框组件的位置
   this.setLayout(layout);
   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   pack();
}
public static void main(String[] args)
{
test11 demo = new test11();
demo.setVisible(true);
}
}

运行效果如下图所示:

下面讨论一下如何自定义一个布局管理器

如果要创建自定义的布局管理器,就必须要创建一个实现了LayoutManager接口的类,可以直接实现它或者实现它的子接口LayoutManager2,每一个自定义布局管理器至少需要实现以下5个方法:

  • void addLayoutCompment(String, Component)
  • void removeLayoutComponent(Component)
  • Dimension preferredLayoutSize(Container)
  • Dimension minimumLayoutSize(Containcr)
  • void LayoutContainer(Container)

除了以上的5个方法之外,布局管理器还通常会实现至少一个公有构造函数和tostring方法.如果希望支持组件布局方向、最大化、最小化、对齐方式等,还需要实现LayoutManager2接口中的5个方法:

  • addLayoutComponent(Component, Object)
  • getLayoutAlignmentX(Container).
  • getLayoutAlignmentY(Container)
  • invalidateLayout(Container).
  • maximumLayoutSize(Container)

在实际的开发中,可以不使用布局管理器,但是这样就无法对每个控件进行定位,使得用户界面很不友好。如果有这样一种情况:一个容器所包含的组件大小不会因为容器的大小、字体、外观感觉以及语言环境的变化而变化,此时布局管理器是可以不需要的,可以使用绝对定位的方式进行定位。绝对定位适用于那种执行专门针对自身并且可能需要知道特定状态的大小、位置计算的自定义容器。但是仍旧建议读者使用布局管理器.因为使用布局管理器能够对控件进行布局,相对来说比较方便,也能够达到客户的要求。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-04 15:07:12

【Java Swing探索之路系列】之三:Java Swing布局管理器组件的相关文章

Java之GUI编程(二)——布局管理器

在上篇博客Java之GUI编程(一)中我已经对GUI编程的组件和事件做了简单介绍了,现在来看看另外一部分关于组件在各个平台是如何做到仍能保持自己合理的位置大小以及外观的. 已经说了Java是跨平台运行的,但是不同的平台对于点及坐标的定义不完全相同.而且屏幕的解析度分辨率不同也会造成位置的变化,为了确保每个组件的相对位置和大小以及外观,java就设计了布局管理器. 布局管理器是对容器中的元素进行管理,按照一定的规则排放容器里面的元素.它控制了组件的摆放. 布局管理器分类: FlowLayout:浮

Java布局管理器组件

Java布局管理器组件 所谓布局管理器,就是为容器内的组件提供若干布局策略,每个容器都拥有某种默认布局管理器,用于负责其内部组件的排列.目前开发中,常用的布局管理器有BorderLayout.FlowLayout.GridLayout.GridBagLayout.CardLayout.BoxLayout.SpringLayout.GroupLayout等: 布局管理器种类 BorderLayout FlowLayout GridLayout GridBagLayout CardLayout Bo

【Java安全技术探索之路系列:Java可扩展安全架构】之四:JCA(三):JCA编程模型

作者:郭嘉 邮箱:[email protected] 博客:http://blog.csdn.net/allenwells github:https://github.com/AllenWell 一 消息摘要 使用MD5计算消息摘要 try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] testdata = { 1, 2, 3, 4, 5 }; md5.update(testdata); byte[] my

swing布局管理器简介

转载:http://stevencjh.blog.163.com/blog/static/1218614612010101775336729/ swing布局管理器简介 一 .BorderLayout布局管理器:BorderLayout 也是一种非常简单的布局策略,它把容器内的空间简单地划分为东.西.南.北.中无个区域,没加入一个组件都应该指明把这个组件加在哪个区域中. BorderLayout是顶层容器( JFrame, JDialog, 和 JApplet )的默认布局管理器.有五个位置组件

【java】浅析java组件中的布局管理器

这篇博文笔者介绍一下java组件中,常用的布局管理器.java组件中的布局方式有好几十种,所有的这些布局管理器都实现了java.awt.LayoutManager接口.接下来笔者介绍一下常用的5种布局管理器,FlowLayout.BorderLayout.GridLayout.GridBagLayout.CardLayout.BoxLayout.如果不希望使用布局管理器,可以调用组件的 setLayout(null); ,但是不建议设置layout为null,因为这样就失去了跨平台特性,和jav

JAVA_布局管理器

1 /* 范例名称:FlowLayout 用法举例 2 * 源文件名称:TestFlowLayout.java 3 * 要 点: 4 * 1. 布局管理器的概念和作用 5 * 2. FlowLayout的性质及用法 6 */ 7 8 import java.awt.*; 9 10 public class TestFlowLayout { 11 public static void main(String args[]) { 12 Frame f = new Frame("Flow Layout

十七、高级布局管理器

1.箱式布局管理器(BoxLayout) 用来管理一组水平或垂直列的组件. 利用Box类提供的6个不可见组件设置箱式布局管理器组件之间的间距. Box类中的两种不可见类型: 支柱(Strut):设置组件的宽度.高度和大小. 胶水(Glue):类似弹簧,将组件平均分布到容器中. 2.卡片布局管理器(CardLayout) 方法:first().last().next().previous().show() 3.网格组布局管理器(GridBagLayou 属性:gridx和gridy.gridwid

(转)Java 的swing.GroupLayout布局管理器的使用方法和实例

摘自http://www.cnblogs.com/lionden/archive/2012/12/11/grouplayout.html (转)Java 的swing.GroupLayout布局管理器的使用方法和实例 GroupLayout 是一个 LayoutManager,它将组件按层次分组,以决定它们在 Container 中的位置.GroupLayout 主要供生成器使用,但也可以手工编码.分组由 Group 类的实例来完成.GroupLayout 支持两种组.串行组 (sequenti

Java Swing 之流式布局管理器

/** * java 之流式布局 * @author gao */ package com.gao; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; @SuppressWarnings("serial") public class Flow