I hear a lot of java programmers complaining about the complexity of GridBagLayout. The GridBagLayout is a bit complicated, but it is also the most flexible layout manager I’ve used in any language. With the aid of a simple utility class it is also the easiest. GridC subclasses GridBagConstraints and provides an easy and concise way to assign properties to components that are added to a GridBagLayout-managed container. Here’s an example:

JPanel p = new JPanel(new GridBagLayout());
p.add(label1, GridC.getc(0,0).label());
p.add(field1, GridC.getc(1,0).field().colspan(2));
p.add(label2, GridC.getc(0,1).label());
p.add(field2, GridC.getc(1,1).field());
p.add(button2, GridC.getc(1,2));

GridC objects have methods for setting virtually every layout property you can think of: column/row spanning, insets, alignment, resize weight along each axis, fill along each axis. Each method returns the same GridC object so that you can chain the calls. For example, the following call puts the component (comp) in location (x,y), spanning two columns, filling along the y axis and aligned to the northEast corner:

p.add(comp, GridC.getc(x, y).colspan(2).filly().northEast())

Please take the GridC code, use it in your projects and rid yourself of GridBagLayout headaches forever.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s