Swing layout managers

Use a GriddedPanel to simplify Swing programming

Anyone who has ever done any Swing programming has had to manipulate layout managers.  Sure, you can use the FlowLayout, but then your controls get placed wherever they seem to fit.   That’s not really what most people want.  GridLayout is pretty easy, but it can lead to unexpected results, because each element of the grid is precisely the same size.  Sooner or later, you’re stuck dealing with GridBagLayout. It’s complicated and the GridBagConstraints are non-intuitive.

In “Swing Second Edition” (see below), the authors present GriddedPanel, which uses a GridBayLayout, but with constraints that are easier to manage and understand.   The idea is that you often want a label and a control to be “glued” together, and placed at the same height as each other. You also often want the corresponding controls to line up vertically, with one another.  However, sometimes, you want a control to be able to expand a bit, if it’s larger than the other controls.

When using GriddedPanel, you use more intuitive methods than what you would use in GridBagLayout:

·        addComponent

·        addAnchoredComponent

·        addFilledComponent

 

Go and look at the source code online.  It’s at www.manning.com/sbe (Chapter 4).  And the book is a great reference for Swing in Java 1.4. Yeah, yeah, 5.0 is out, but you may take a while to transition to it anyhow.

 

Swing Second Edition, Matthew Robinson and Pavel Vorobiev, Manning  Publications Company, 2003.  ISBN 1930110-88-X

 

Online source
Source code for Swing Second Edition