swing 网格布局管理器GridBagLayout

public class GraidBagLearn {

  

   public staticvoid addComponentsToPane(Containerpane){

      JButtonbutton;

      pane.setLayout(new GridBagLayout());

      GridBagConstraintsc=new GridBagConstraints();

      c.fill=GridBagConstraints.HORIZONTAL;

      c.weightx=0.5;

     

      button=new JButton("Button1");

      c.gridx=0;

      c.gridy=0;

      pane.add(button,c);

     

      button=new JButton("Button2");

      c.gridx=1;

      c.gridy=1;

      pane.add(button,c);

     

      button=new JButton("Button3");

      c.ipady=40;

      c.weightx=0;

      c.gridwidth=2;

      c.gridx=0;

      c.gridy=2;

      pane.add(button,c);

     

      button=new JButton("Button4");

      c.ipady=0;

      c.weighty=1;

      c.anchor=GridBagConstraints.PAGE_END;

      c.insets=newInsets(10,0,0,0);

      c.gridx=1;

      c.gridy=3;

      pane.add(button,c);

 

   }

  

   private staticvoid createAndShowGUI() {

       //Create and set up the window.

       JFrame frame = new JFrame("GridBagLayoutDemo");

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

       //Set up the content pane.

       addComponentsToPane(frame.getContentPane());

 

       //Display the window.

       frame.pack();

       frame.setVisible(true);

    }

   public staticvoid main(String[] args) {

      javax.swing.SwingUtilities.invokeLater(new Runnable() {

           public void run() {

                createAndShowGUI();

           }

       });

 

   }

}

网格布局类似html中的表格,它将面板分成一排排,一列列的小格,将控件添加到这些小格中。GridBagConstraints指定了要添加控件的属性。

Ø  gridxgridy指定添加到那个小格中。

Ø  gridwidth, gridheight指定在水平和竖直上分别要占几个小格。

Ø  如果一排有两个控件,一个的weightx0.3,另一个的为0.7那么当把窗口拉大,水平多出100像素时,有30个分配给第一个控件,有70个分配给第二个。默认值为0,表示不分配。这是个相对值,上面指定为37效果一样。同理weighty指定竖直方向上的分配。

Ø  c.fill=GridBagConstraints.HORIZONTAL;这个表示当格子比控件大时,控件在水平方向上充满格子,水平方向不变。还可以指定为竖直,或两者都是。

Ø  c.anchor=GridBagConstraints.LAST_LINE_END;这个指定当控件比格子小时,控件应显示在那个位置,也就是上下左右,左上角,右上角等等。当然用fill指定了充满格子时,这个就没用了。

Ø  c.insets=new Insets(10,0,0,0);这个指定了格子的外边框。也就是与别的格子的间距。

c. ipady=40;这类属性用来调整格子的大小,不同列不同行的格子大小可以不同。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值