首页 > 代码库 > Java GridBagLayout 简单使用

Java GridBagLayout 简单使用

    这里只介绍了很基础布局构建及使用,主要是关于 GridBagLayout.

    首先整套流程大概是,

    声明一个 GridBagLayout 对象

    private GridBagLayout gridBagLayoutFrame = new GridBagLayout();

 

    然后把当前类的容器布局管理器设置为 GridBagLayout

    this.setLayout(gridBagLayoutFrame);

 

    最后声明一个 JPanel 用于添加组件。(当然也可以是别的Panel。如JTabbedPane等)

    private JPanel checkBoxTreePanel = new JPanel();

    private JTabbedPane tabbedPane = new JTabbedPane();

 

    然后就可以开始使用这个布局管理器来增加和设置组件了。

  add(Component comp, Object constraints)

    下面是一个例子:

   

 1 import java.awt.*;
 2 import javax.swing.JFrame;
 3 import javax.swing.JTabbedPane;
 4 import javax.swing.JPanel;
 5 
 6 
 7 public class WriteForBlog extends JFrame
 8 {
 9     private GridBagLayout gridBagLayoutFrame = new GridBagLayout();
10     private JTabbedPane tabbedPane = new JTabbedPane();
11     private JPanel panelOne = new JPanel();
12     private JPanel panelTwo = new JPanel();
13     
14     public WriteForBlog()
15     {
16         jbInit();
17     }
18     
19     private void jbInit()
20     {
21         this.setLayout(gridBagLayoutFrame);
22         this.setBounds(200, 200, 1000, 600);
23         tabbedPane.add(panelOne, "One");
24         tabbedPane.add(panelTwo, "Two");
25         
26         this.add(tabbedPane, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
27                  ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
28     }
29     
30     public static void main(String[] args)
31     {
32         WriteForBlog test = new WriteForBlog();
33         test.setVisible(true);
34     }
35 
36 }

    效果图:

技术分享

   

   

Java GridBagLayout 简单使用