Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container

Creating a Custom Layout Manager

Note: Before you start creating a custom layout manager, make sure that no existing layout manager will work. In particular, GridBagLayout is flexible enough to work in many cases.

To create a custom layout manager, you must create a class that implements the LayoutManager interface. LayoutManager requires its adherents to implement five methods:

public void addLayoutComponent(String name, Component comp)
Called only by the Container add(name, component) method. Layout managers that don't require that their components have names generally do nothing in this method.

public void removeLayoutComponent(Component comp)
Called by the Container remove() and removeAll() methods. Layout managers that don't require that their components have names generally do nothing in this method, since they can query the container for its components using the Container getComponents() method.

public Dimension preferredLayoutSize(Container parent)
Called by the Container preferredSize() method, which is itself called under a variety of circumstances. This method should calculate the ideal size of the parent, assuming that the components it contains will be at or above their preferred sizes. This method must take the parent's internal borders (returned by the Container insets() method) into account.

public Dimension minimumLayoutSize(Container parent)
Called by the Container minimumSize() method, which is itself called under a variety of circumstances. This method should calculate the minimum size of the parent, assuming that the components it contains will be at or above their minimum sizes. This method must take the parent's internal borders (returned by the Container insets() method) into account.

public void layoutContainer(Container parent)
Called when the container is first displayed, and every time its size changes. A layout manager's layoutContainer() method doesn't actually draw Components. It simply invokes each Component's resize(), move(), and reshape() methods to set the Component's size and position. This method must take the parent's internal borders (returned by the Container insets() method) into account. You can't assume that the preferredLayoutSize() or minimumLayoutSize() method will be called before layoutContainer() is called.

Besides implementing the five methods required by LayoutManager, layout managers generally implement at least one public constructor and the toString() method.

Here's source code for a custom layout manager named DiagonalLayout. It lays out components diagonally, from left to right, with one component per row.

Here's an example of DiagonalLayout in action:


Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:


Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container