Layout Managers

Layout Managers should almost always be used. Hard coding positions and sizes is usually not appropriate.

Most common layouts:

Least common layouts: Layout Managers are often mixed together in a single frame or dialog, where a top level container has its own Layout Manager (often a BoxLayout or BorderLayout), and smaller parts use their own layout, completely independent of the others.

Please see the topic on JGoodies Forms for an interesting alternative to the standard JDK classes for layouts.

Example 1

Here's an example of a dialog box which uses four nested BoxLayout objects to arrange its elements. The brightly colored areas group elements which share the same BoxLayout :

Highlighted layout managers

Red - (vertical layout) "struts" provide uniform spacing around each JButton, while "glue" takes up the remaining extra space below the Delete button

Blue - (horizontal layout) again, struts provide uniform spacing around each JButton, and glue takes up the remaining extra space to the left of the OK button.

Black - (horizontal layout) contains the JTable and the Add-Change-Delete buttons

Yellow - (vertical layout) the top level container for Black and Blue

Yellow and Blue form a standardized dialog, in which top level layout and the OK, Cancel buttons are defined by an abstract base class. Concrete subclasses define both the contents of Black and the action taken by the OK button.

The sizing and alignment of JButton objects in BoxLayout is not automatic, unfortunately. See Common utility tasks for these related utility methods :

Example 2

Here's a typical data entry dialog :

Highlighted layout managers

Blue - the standardized command row (same as Example 1)

Black - uses GridBagLayout.  See Common utility tasks for these utility methods related to GridBagLayout and GridBagConstraints :

Yellow - the standardized top level layout (same as Example 1)

See Also :
Standardized dialogs
Swing utility tasks
Consider JGoodies Forms for layouts
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -