What is a LayoutManager?

When you add a component to an applet or a container, the container uses its layout manager to decide where to put the component. Different LayoutManager classes use different rules to place components.

java.awt.LayoutManager is an interface. Five classes in the java packages implement it:

A FlowLayout arranges widgets from left to right until there's no more space left. Then it begins a row lower and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. A FlowLayout is useful for laying out buttons but not for much else. This is the default LayoutManager for applets and panels (special containers to aid with layouts about which you'll learn more very shortly).

A BorderLayout organizes an applet into North, South, East, West and Center sections. North, South, East and West are the rectangular edges of the applet. They're continually resized to fit the sizes of the widgets included in them. Center is whatever's left over in the middle.

A CardLayout breaks the applet into a deck of cards, each of which has its own LayoutManager. Only one card appears on the screen at a time. The user flips between cards, each of which shows a different set of components. The common analogy is with HyperCard on the Mac and Toolbook on Windows. In Java this might be used for a series of data input screens, where more input is needed than can comfortably be fit on one screen.

A GridLayout divides an applet into a specified number of rows and columns which form a grid of cells, each equally sized and spaced. As Components are added to the layout they are placed in the cells, starting at the upper left hand corner and moving to the right and down the page. Each component is sized to fit into its cell. This tends to squeeze and stretch components unnecessarily. However the GridLayout is great for arranging Panels.

GridBagLayout is the most precise of the five AWT LayoutManagers. It's similar to the GridLayout, but components do not need to be the same size. Each component can occupy one or more cells of the layout. Furthermore components are not necessarily placed in the cells beginning at the upper left-hand corner and moving to the right and down.

In simple applets with just a few components you often need only one layout manager. In more complicated applets, however, you'll often split your applet into panels, lay out the panels according to a layout manager, and give each panel its own layout manager that arranges the components inside it.


Previous | Next | Top
Last Modified August 12, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu