Designing a Window Layout

Problem

The default layout isn’t good enough.

Solution

Learn to deal with a layout manager.

Discussion

The container classes such as Panel have the ability to contain a series of components. But there are many ways of arranging the components within a window. Rather than clutter up each container with a variety of different layout computations, the designers of the Java API used a sensible design pattern to divide the labor. A layout manager is an object that performs the layout computations for a container.[29] There are five common layout manager classes in the AWT package (see Table 13-1), plus a few more specialized ones in javax.swing. Plus, as we’ll see in Section 13.15, it’s not that big a deal to write your own!

Table 13-1. Layout managers

Name

Notes

Default on

FlowLayout

Flows across the container

(J)Panel, (J)Applet

BorderLayout

Five “geographic” regions

(J)Frame, (J)Window

GridLayout

Regular grid (all items same size)

None

CardLayout

Display one of many components at a time; useful for wizard-style layouts

None

GridBagLayout

Very flexible but maximally complex

None

Since we’ve broached the subject of layout management, I should mention that each component has a method called getPreferredSize( ) , which the layout managers use in deciding how and where to place components. A well-behaved component overrides this method to return something meaningful. A button or label, for example, will indicate that it wishes ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.