摘自http://bbs.csdn.net/topics/340189065 使用GridBagLayout控制行列的高度和宽度
gridwidth 指定组件显示区域的某一行中的单元格数。 默认值1,水平占一格
gridheight 指定在组件显示区域的一列中的单元格数。默认值1,垂直占一格
weightx 指定如何分布额外的水平空间。 默认值0,额外水平空间不分配。
weighty 指定如何分布额外的垂直空间。 默认值0,额外垂直空间不分配。
ipadx 指定组件最小宽度,可确保组件不会过份缩放。
ipady 指定组件最小高度,可确保组件不会过份缩放。
gridx 指定组件左上角所在位置横坐标。
gridy 指定组件左上角所在位置纵坐标。
inserts 在组件周围增加空白区域。
anchor 单个组件水平、垂直都不填充时,设置组件应该显示在区域的哪个方位,西北还是东南。 也就是说anchor 和fill互斥,fill优先级高
拉伸后效果如下
package com.hw.gridbaglayout; import java.awt.Button;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import javax.swing.JFrame;
import javax.swing.JPanel; public class GridBagEx2 extends JPanel
{
private static final long serialVersionUID = -5214441555967215113L; 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[])
{
JFrame f = new JFrame("GridBag Layout Example");
f.setLocation(400, 200);
GridBagEx2 ex1 = new GridBagEx2(); ex1.init(); f.add("Center", ex1);
f.pack();
f.setSize(f.getPreferredSize());
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ @Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
} });
} }