终于用到一种如此灵活的布局了,她就是:GridBagConstraints,今天主要看了如下四个属性,改天在继续研究。
gridwidth: 指定在组件显示区域的一行中的单元格数。即组件在水平方向所占用的单元格个数
gridheight:指定在组件显示区域的一列中的单元格数。即组件在垂直方向所占用的单元格个数
参照如下代码:package j2se.layout;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
public class GridBagLayoutTes3 extends JFrame {
public void makebutton(JFrame frame, String name, GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
c.fill = GridBagConstraints.BOTH;
frame.add(button);
}
public static void main(String[] args) {
GridBagLayoutTes3 test = new GridBagLayoutTes3();
JFrame frame = new JFrame("Test");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
frame.setSize(400, 200);
frame.setLayout(gridbag);
// 创建一个3*4的表格,前三个button为一行
test.makebutton(frame, "Button1", gridbag, c);
test.makebutton(frame, "Button2", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; // 第一行结束
test.makebutton(frame, "Button3", gridbag, c);
// 即将添加的button占两列宽度
c.gridwidth = 2;
test.makebutton(frame, "Button4", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; // 第二行结束
test.makebutton(frame, "Button5", gridbag, c);
// 即将添加的button占两行高度,一列宽度
c.gridheight = 2;
c.gridwidth = 1;// 每次使用完之后,记得要清除上次的状态,否则此时的gridwidth还是上次的GridBagConstraints.REMAINDER哦
test.makebutton(frame, "Button6", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; // 第三行结束
c.gridheight = 1;//重置占用的高度为1行高度
test.makebutton(frame, "Button7", gridbag, c);
test.makebutton(frame, "Button8", gridbag, c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
结果如图:
gridx:指定包含组件的显示区域开始边的单元格,其中行的第一个单元格为 gridx=0。 即指定组件所在的行的位置
gridy:指定位于组件显示区域的顶部的单元格,其中最上边的单元格为 gridy=0。 即指定组件所在的列的位置。
实际就是一组x,y坐标。
参照如下代码:
package j2se.layout;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
public class GridBagLayoutTes2 extends JFrame {
public void makebutton(JFrame frame, String name, GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
c.fill = GridBagConstraints.BOTH;
frame.add(button);
}
public static void main(String[] args) {
GridBagLayoutTes2 test = new GridBagLayoutTes2();
JFrame frame = new JFrame("Test");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
frame.setSize(600, 400);
frame.setLayout(gridbag);
//此处绘制一个3*3的表格
c.gridx = 0;
c.gridy = 0;
test.makebutton(frame, "Button1", gridbag, c);//Button1将被放在(0,0)位置
c.gridx = 2;
c.gridy = 2;
test.makebutton(frame, "Button2", gridbag, c);//Button2将被放在(2,2)位置
c.gridx = 1;
c.gridy = 1;
test.makebutton(frame, "Button3", gridbag, c);//Button3将被放在(1,1)位置
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
结果如图: