Java界面设计之页面管理器
作者:网络转载 发布时间:[ 2013/4/8 10:31:19 ] 推荐标签:
4、GridBagLayout 这个布局方式是复杂的,它动态的给每一个组件精确的进行位置的约束,为此还专门有个约束的对象GridBagConstraints,总共有11个参数能够对组件进行约束; GridBagConstraints(int gridx,int gridy,int gridwidth,int gridheight,double weightx,double weighty,int anchor,int fill, Insets,int ipadx,int ipady);
gridx和gridy是组件在网格中的位置,这位置的计算方法非常有趣,类似与直角坐标系里面的位置分布;
gridwidth和gridheight 这俩个参数是设置组件在表格当中的大小的,设置的时候要小心一点,自己要有一个界面的草图在旁边参考;
weightx和weighty参数可以设置当你的窗口被拉大(或拉小)的时候,组件所按照什么比例进行缩放,数字越大,组件变化的会越大;
anchor 参数是有两个组件,相对小的的组件应该放在哪里;
fill 参数是当组件所处的动态表格里面有空余的位置的时候,组件将按什么方向填充,这个参数在界面中比较关键一点;
Insets 参数是一个小的对象,其中也有4个不同的参数,分别是上,左,右,下来设置组件之间的间距;
ipadx和ipady是组件边框离组件中心的距离,对有些组件来说这个参数是没有必要的;
感觉有很多的参数来设置一个组件,还有专门的约束对象,其实每次并不是哪一个参数都要重新设置的,下面是一个例子
import javax.swing.*;
import java.awt.*;
public class GridBagLayout1 {
public GridBagLayout1(){
JFrame frame =new JFrame();
GridBagLayout grid=new GridBagLayout();
GridBagConstraints c1=new GridBagConstraints();
frame.setLayout(grid);
//为button1进行约束
c1.gridwidth=2; c1.gridheight=1;
c1.insets=new Insets(5,5,0,0); //和上面的组件间距为5,右边为间距5
JButton button1=new JButton("button1");
grid.setConstraints(button1,c1);
frame.add(button1);
//为button2进行约束
c1.fill=GridBagConstraints.HORIZONTAL;
JButton button2=new JButton("button2");
grid.setConstraints(button2,c1);
frame.add(button2);
//为button3进行约束
c1.gridx=0; c1.gridy=1; //动态表格(0,1)位置
c1.gridwidth=4; //组件长占4个单元格,高占一个单元格
JButton button3=new JButton("button3");
grid.setConstraints(button3,c1);
frame.add(button3);
frame.setVisible(true);
frame.setSize(200,150);
}
public static void main(String[] args) {
new GridBagLayout1();
}
}

sales@spasvo.com