In this discussion, we will look at the various layout managers provided by the AWT. Just as their name implies, layout managers assume responsibility for the fine-grain layout of the user interface in accord with general specifications provided by the programmer. These specifications range from simply indicating the items to be laid out to rather detailed constraints that provide considerable direction as to how the layout is to be done. We will also look at the most precise layout "manager" available: no layout manager. It gives the programmer explicit control over the x-y coordinates and the exact width and height of each component.
This discussion is presented with respect to Java 1.1. It will refer to the Java class hierarchy and, specifically, to AWT classes. A discussion based on Java 1.0 is also available.
Specific Layout Managers
The five layout managers provided by the Java AWT plus the no layout manager option are described below.
FlowLayout
The
FlowLayout
manager is the default Layout Manager forApplets
andPanels
. It is the most basic of the layout managers. It places components, left to right, within the container. If it runs out of room on one "line," it wraps around to the next line.BorderLayout
The
BorderLayout
manager is the default Layout Manager forFrames
. It places one component in the center of the Frame and four components at the top, bottom, left, and right margins.GridLayout
The
GridLayout
manager tiles the enclosing container. It organizes components in a two-dimensional grid, specified in the constructor. Components are added, beginning with the top left corner, left to right, from top row to bottom row.CardLayout
The
CardLayout
manager enables you to create multiple interfaces, like cards in a deck, and shuffle among them.GridBagLayout
The
GridBagLayout
manager is the most flexible but most complex of the layout mangers. The idea behind GridBagLayout is that you divide the display in cells (rows and columns), similar to a GridLayout. However, the difference is that the various cells can have different sizes. Furthermore, as the window is resized, the components within the cells are resized in accord with their respective constraints and not uniformly.No Layout Manager
While the GridBagLayout manager provides you with considerable flexibility, it is also rather Byzantine in its complexity. If your window does not require resizing, you may find it preferable to provide explicit coordinates, width, and height for each component in the interface. If this is practical, you may use the No Layout manger option.
References
References useful for this discussion include the following:
- Sun's Java Development Kit (JDK)
- Sun's Java API
- Java API Class Hierarchy
- Source Code for JDK Packages