GridBagLayout布局管理器比较复杂,参数也比较多,参数是
newGridBagConstraints(gridx,gridy,gridwidth,gridheight,weightx,weighty,anchor,fill,insert,ipadx,ipady);
每个参数的含义
gridx,gridy
设置组件的位置,gridx设置为GridBagConstraints.RELATIVE代表此组件位于之前所加入组件的右边。
gridy设置为GridBagConstraints.RELATIVE代表此组件位于以前所加入组件的下面。
建议定义出gridx,gridy的位置以便以后维护程序。gridx=0,gridy=0时放在0行0列。
gridwidth,gridheight
用来设置组件所占的单位长度与高度,默认值皆为1。
你可以使用GridBagConstraints.REMAINDER常量,代表此组件为此行或此列的最后一个组件,而且会占据所有剩余的空间。
weightx,weighty
用来设置窗口变大时,各组件跟着变大的比例。
当数字越大,表示组件能得到更多的空间,默认值皆为0。
anchor
当组件空间大于组件本身时,要将组件置于何处。
有CENTER(默认值)、NORTH、NORTHEAST、EAST、SOUTHEAST、WEST、NORTHWEST选择。
insets
设置组件之间彼此的间距。
它有四个参数,分别是上,左,下,右,默认为(0,0,0,0)。
ipadx,ipady
设置组件间距,默认值为0。
下面是一个小例子
package com.dr.swt.xuechengxitong;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public class Teste3 extends JFrame{
private static JTextArea jTextArea;
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
public Teste3(){
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
JScrollPane scroll = new JScrollPane(getJtextArea(),
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
gridbag.setConstraints(scroll, new GridBagConstraints(0, 0, 3,
2, 1.0, 1.0,GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(100, 100, 100, 100),
0, 0));
gridbag.setConstraints(getJButton1(), new GridBagConstraints
(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.SOUTH,
GridBagConstraints.HORIZONTAL, new Insets(30, 200, 100,
100), 0, 0));
gridbag.setConstraints(getJButton2(), new GridBagConstraints
(1, 2, 1, 1, 1.0, 0.0,GridBagConstraints.SOUTH,
GridBagConstraints.HORIZONTAL, new Insets(30, 100, 100,
100), 0, 0));
gridbag.setConstraints(getJButton3(), new GridBagConstraints
(2, 2, 1, 1, 1.0, 0.0,GridBagConstraints.SOUTH,
GridBagConstraints.HORIZONTAL, new Insets(30, 100, 100,
200), 0, 0));
this.add(scroll);
this.add(getJButton1());
this.add(getJButton2());
this.add(getJButton3());
Dimension screenSize = Toolkit.getDefaultToolki().
getScreenSize();
int screenWidth = (int) screenSize.getWidth();
int screenHight = (int) screenSize.getHeight();
this.setSize(screenWidth, screenHight);
this.setVisible(true);
}
private JTextArea getJtextArea(){
if(jTextArea == null){
jTextArea = new JTextArea();
jTextArea.setLineWrap(true);
}
return jTextArea;
}
private JButton getJButton1(){
if(jButton1 == null){
jButton1 = new JButton("jButton1");
}
return jButton1;
}
private JButton getJButton2(){
if(jButton2 == null){
jButton2 = new JButton("jButton2");
}
return jButton2;
}
private JButton getJButton3(){
if(jButton3 == null){
jButton3 = new JButton("jButton3");
}
return jButton3;
}
public static void main(String args[]){
new Teste3();
}
}