O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required