Laying Out Components within a Container |
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()
andremoveAll()
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 ContainergetComponents()
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 Containerinsets()
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 Containerinsets()
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'sresize()
,move()
, andreshape()
methods to set the Component's size and position. This method must take the parent's internal borders (returned by the Containerinsets()
method) into account. You can't assume that thepreferredLayoutSize()
orminimumLayoutSize()
method will be called beforelayoutContainer()
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:
Laying Out Components within a Container |