自己想做个小程序,却在布局上犯了难,使用FlowLayout和BorderLayout这些功能不够强大,使用GridBagLayout却不会,只好求助于文档了。
文档对这个布局管理器介绍很详细,但是最痛苦的是英文。不过幸好它有实例,经过在网上查阅和推敲实例,终于对GridBagLayout的使用有了一个成型的了解,拿出来与大家分享。
GridBagLayout是一个灵活的布局管理器,部件如果想加入其中需借助GridBagConstraints,其中有若干个参数,解释如下:
gridx/gridy:组件的横纵坐标
gridwidth:组件所占列数,也是组件的宽度
gridheight:组件所占行数,也是组件的高度
fill:当组件在其格内而不能撑满其格时,通过fill的值来设定填充方式,有四个值
ipadx: 组件间的横向间距
ipady:组件间的纵向间距
insets:当组件不能填满其格时,通过insets来指定四周(即上下左右)所留空隙
anchor:同样是当组件不能填满其格时,通过anchor来设置组件的位置,anchor有两种值,绝对和相对的值分别有 若干个,文档中有,可自行查看
weightx:行的权重,通过这个属性来决定如何分配行的剩余空间
weighty:列的权重,通过这个属性来决定如何分配列的剩余空间
还是文档实用,用例子来说话
import java.awt.*;
import java.util.*;
import java.applet.Applet;
public class GridBagEx1 extends Applet {
protected void makebutton(String name,
GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
add(button);
}
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(gridbag);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
makebutton("Button1", gridbag, c);
makebutton("Button2", gridbag, c);
makebutton("Button3", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; //end row
makebutton("Button4", gridbag, c);
c.weightx = 0.0; //reset to the default
makebutton("Button5", gridbag, c); //another row
c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row
makebutton("Button6", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; //end row
makebutton("Button7", gridbag, c);
c.gridwidth = 1; //reset to the default
c.gridheight = 2;
c.weighty = 1.0;
makebutton("Button8", gridbag, c);
c.weighty = 0.0; //reset to the default
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.gridheight = 1; //reset to the default
makebutton("Button9", gridbag, c);
makebutton("Button10", gridbag, c);
setSize(300, 100);
}
public static void main(String args[]) {
Frame f = new Frame("GridBag Layout Example");
GridBagEx1 ex1 = new GridBagEx1();
ex1.init();
f.add("Center", ex1);
f.pack();
f.setSize(f.getPreferredSize());
f.setVisible(true);
}
}
可以自行运行,查看其结果
文档对其各个按钮的参数设定解释如下:
weightx = 1.0
weightx = 1.0
, gridwidth = GridBagConstraints.REMAINDER
gridwidth = GridBagConstraints.REMAINDER
gridwidth = GridBagConstraints.RELATIVE
gridwidth = GridBagConstraints.REMAINDER
gridheight = 2
, weighty = 1.0
gridwidth = GridBagConstraints.REMAINDER
gridheight = 2
,
weighty = 1.0,即它占用两行一列(其实这个一列和两行都是相对的)。这一行还没封口,所以后面来的button9加在了这一行,因为它gridwidth = GridBagConstraints.REMAINDER,所以第四行封口。