Layout Management

Once you have created your components and added them to containers, the next step is to arrange those components within the container. This is called layout management and is almost always performed by a special object known as a layout manager. Layout managers are implementations of the java.awt.LayoutManager interface or its LayoutManager2 subinterface. Each particular LayoutManager implementation enforces a specific layout policy and automatically arranges the components within a container according to that policy. The sections that follow demonstrate the use of each of the AWT and Swing layout managers. Note that BoxLayout is the only layout manager defined by Swing. Although Swing defines many new components, Swing GUIs typically rely on AWT layout managers.

You create a layout manager as you would any other object. Different layout manager classes take different constructor arguments to specify the parameters of their layout policy. Once you create a layout manager, you do not usually invoke its methods. Instead, you pass the layout manager object to the setLayout( ) method of the container that is to be managed; the container invokes the various LayoutManager methods when necessary. Once you have set the layout manager, you can usually forget about it.

As you’ll see in the following sections, most of the predefined AWT layout managers have fairly simple layout policies that may not seem like much use on their own. Their power becomes apparent when combined, ...

Get Java Examples in a Nutshell, 3rd Edition 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.