Sử dụng phương thức ‘setConstraints()’ để thiết lập các hằng số cho mỗi thành phần. Cho
ví dụ:
gblay.setConstraints(lb1, gbc);
‘gblay’ là đối tượng của lớp GridBagLayout, lbl là thành phần ‘Label’ và ‘gbc’ là đối tượng
của lớp GridBagConstraints.
Chương trình 5.12 minh họa một ví dụ của GridBagLayout và GridBagConstraints.
Chương trình 5.12
import java.awt.*;
class Gbltest extends Frame
{
TextArea ta;
TextField tf;
Button b1,b2;
CheckboxGroup cbg;
Checkbox cb1,cb2,cb3,cb4;
GridBagLayout gb;
GridBagConstraints gbc;
public GBltest(String title)
{
super(title);
gb=new GridBagLayout();
setLayout(gb);
gbc=new GridBagConstraints();
ta=new TextArea(“Textarea”,5,10);
tf=new TextField(“enter your name”);
b1=new Button(“TextArea”);
b2=new Button(“TextField”);
cbg=new CheckboxGroup();
cb1=new Checkbox(“Bold”, cbg,false);
cb2=new Checkbox(“Italic”, cbg,false);
cb3=new Checkbox(“Plain”, cbg,false);
cb4=new Checkbox(“Bold/Italic”, cbg,true);
gbc.fill=GridBagConstraints.BOTH;
addComponent(ta,0,0,4,1);
gbc.fill=GridBagConstraints.HORIZONTAL;
addComponent(b1,0,1,1,1);
gbc.fill=GridBagConstraints.HORIZONTAL;
addComponent(b2,0,2,1,1);