GridBagLayout is your friend
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.
Leave a comment
You must be logged in to post a comment.