Subpages: 1. Layouts overview
2. Comparing common layout managers
3. Using GridBagLayout
4. Choosing the right layout
5. Custom layout manager: part I -Label/field pairs
6. Custom layout manager: part II - Common interfaces
7. Dynamic layout in a JavaBeans container
Chapter 4. Layout Managers
In this chapter:
- Layouts overview
- Comparing common layout managers
- Using GridBagLayout, by James Tan
- Choosing the right layout
- Custom layout manager: part I - Label/field pairs
- Custom layout manager: part II - Common interfaces
- Dynamic layout in a JavaBeans container
4.1 Layouts overview
In this chapter we present several examples showing how to use various layouts to satisfy specific goals, and how to create two custom layout managers that simplify the construction of many common interfaces. We also show how to construct a basic container for JavaBeans which must be able to manage a dynamic number of components. But before we present these examples it is helpful to understand the big picture of layouts, which classes use their own custom layouts, and exactly what it means to be a layout manager.
All layout managers implement one of two interfaces defined in the java.awt package: LayoutManager or its subclass, LayoutManager2. LayoutManager declares a set of methods that are intended to provide a straight-forward, organized means of managing component positions and sizes in a container. Each implementation of LayoutManager defines these methods in different ways accoring to its specific needs. LayoutManager2 enhances this by adding methods intended to aid in managing component postitions and sizes using constraints-based objects. Constraints-based objects usually store position and sizing information about one component and implementations of LayoutManager2 normally store one contraints-based object per component. For instance, GridBagLayout uses a Hashtable to map each Component it manages to its own GridBagConstraints object.
Figure 4.1 shows all the classes implementing LayoutManager and LayoutManager2. Note that there are several UI classes implementing these interfaces to provide custom layout functionality for themselves. The other classes--the classes we are most familar and concerned with--are built solely to provide help in laying out containers they are assigned to.
Each container should be assigned one layout manager, and no layout manager should be used to manage more than one container.
Figure 4.1 LayoutManager and LayoutManager2 implementations
abstract interface java.awt.LayoutManager
This interface must be implemented by any layout manager. Two methods are especially noteworthy:
layoutContainer(Container parent) calculates and sets the bounds for all components in the given container.
preferredLayoutSize(Container parent) calculates the preferred size requirements to lay out components in the given container and returns a Dimension instance representing this size.
abstract interface java.awt.LayoutManager2
This interface extends LayoutManager to provide a framework for those layout managers that use constraints-based layouts. Method addLayoutComponent(Component comp, Object constraints) adds a new component associated with a constraints-based object which carries information about how to lay out this component.
A typical implementation is BorderLayout which requires a direction (north, east, etc.) to position a component. In this case the constraint objects used are static Strings such as BorderLayout.NORTH, BorderLayout.EAST, etc. We are normally blind to the fact that BorderLayout is constraints-based because we are never required to manipulate the constraint objects at all. This is not the case with layouts such as GridBagLayout, where we must work directly with the contraint objects (instances of GridBagConstraints).
BoxLayout organizes the components it manages along either the x-axis or y-axis of the owner panel. The only constructor, BoxLayout(Container target, int axis), takes a reference to the Container component it will manage and a direction (BoxLayout.X_AXIS or BoxLayout.Y_AXIS). Components are laid out according to their preferred sizes and not wrapped, even if the container does not provide enough space.
To make using the BoxLayout manager easier, Swing also provides a class named Box which is a container with an automatically assigned BoxLayout manager. To create an instance of this container we simply pass the desired alignment to its constructor. The Box class also supports the insertion of invisible blocks (instances of Box.Filler--see below) allowing regions of unused space to be specified. These blocks are basically lightweight components with bounds (position and size) but no view.
static class javax.swing.Box.Filler
This static inner class defines invisible components that affect a container's layout. The Box class provides convenient static methods for the creation of three different variations: glue, struts, and rigid areas.
createHorizontalGlue(), createVerticalGlue(): returns a component which fills the space between its neighboring components, pushing them aside to occupy all available space (this functionality is more analagous to a spring than it is to glue).
createHorizontalStrut(int width), createVerticalStrut(int height): returns a fixed-width (height) component which provides a fixed gap between its neighbors.
createRigidArea(Dimension d): returns an invisible component of fixed width and height.
This is a simple layout which places components from left to right in a row using the preferred component sizes (i.e. size returned by getPreferredSize()) until no space in the container is available. When no space is available a new row is started. Because this placement depends on the current size of the container we cannot always guarantee in advance which row a component will be placed in.
FlowLayout is too simple to rely on in serious applications where we want to be sure, for instance, that a set of buttons will reside at the bottom of a dialog and not on it's right side. However, it can be useful as a pad for a single component to ensure that this component will be placed in the center of a container. Note that FlowLayout is the default layout for all JPanels (the only exception is the content pane of a JRootPane which is always initialized with a BorderLayout).
This layout places components in a rectangular grid. There are three constructors:
GridLayout(): creates a layout with one column per component. Only one row is used.
GridLayout(int rows, int cols): creates a layout with the given number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap): creates a layout with the given number of rows and columns, and the given size of horizontal and vertical gaps between each row and column.
GridLayout places components from left to right and from top to bottom assigning the same size to each. It forces occupation of all available container space and shares this space evenly between components. When not used carefully this can lead to undesirable component sizing, such as text boxes three times higher than expected.
class java.awt.GridBagLayout, class java.awt.GridBagConstraints
This layout extends the capabilities of GridLayout to become constraints-based. It breaks the container's space into equal rectangular pieces (like bricks in a wall) and places each component in one or more of these pieces. You need to create and fill a GridBagConstraints object for each component to inform GridBagLayout how to place and size that component.
GridBagLayout can be effectively used for placement of components, if no special behavior is required on resizing. However, due to it's complexity it usually requires some helper methods or classes to handle all necessary constraints information. James Tan, a usability expert and GridBagLayout extraordinaire, gives a comprehensive overview of this manager in section 4.3. He also presents a helper class to ease the burden of dealing with GridBagConstraints.
This layout divides a container into five regions: center, north, south, east, and west. To specify the region to place a component in we use Strings of the form "Center," "North," etc., or the static String fields defined in BorderLayout: BorderLayout.CENTER, BorderLayout.NORTH, etc. During the layout process, components in the north and south regions will first be alotted their preferred height (if possible) and the width of the container. Once south and north components have been assigned sizes, components in the east and west regions will attempt to occupy their preferred width and any remaining height between the north and south components. A component in the center region will occupy all remaining available space. BorderLayout is very useful, especially in conjunction with other layouts as we will see in this and future chapters.
CardLayout treats all components similar to cards of equal size overlapping one another. Only one card component is visible at any given time (figure 4.2 illustrates). Methods first(), last(), next(), previous(), and show() can be called to switch between components in the parent Container.
Figure 4.2 CardLayout
In a stack of several cards, only the top-most card is visible. The following code a simple CardLayout demo, which endlessly flips through four cards containing buttons.
This class represents a generic lightweight container. It works in close cooperation with layout managers. The default constructor creates a JPanel with FlowLayout, but different layouts can be specified in the constructor or assigned using the setLayout() method (see chapter 3 for more about JPanel).