A layout manager determines the location and size of components placed into a container. Different layout manager classes use different algorithms for determining size and location.
Most of the Swing containers have special built-in layout managers. The exception is the JPanel class. It uses a Strategy design pattern allowing programmers to plug in the layout manager that best suits their purpose. The only layout manager methods that are normally used are constructors.
A FlowLayout places components in rows. Each component is given its preferred size. When a row has as many components as can fit, a new row is started.
This is the default layout manager for JPanel. There are three useful constructors.
A BorderLayout divides its container into three horizontal stripes: the top (north), the middle, and the bottom (south). At most one component can be placed into the north or south. These components get their preferred height, but they take up the full width of the container.
The middle stripe get whatever height is available after deducting the heights of the north and south components. It can hold three components: one on the left (west), one in the middle (center), and one on the right (east). The east and west components get their preferred widths, but they take up the full height of the middle stripe.
This is the default layout manager for content panes. There are two useful constructors.
When components are added to a container that uses a BorderLayout, they should be added with the following kind of statement.
container.add(component, whr);
The parameter whr should be one of the following.
A GridLayout places components in a rectangular grid whose cells all have the same size. Each component is sized to fill the cell.
There are two useful GridLayout constructors.
A BoxLayout places components into a single row or column, as specified
by the second constructor parameter.
For a row (parameter value BoxLayout.X_AXIS
), each
component get its preferred height.
The widths are adjusted according to a formula that incorporates both
preferred and maximum widths.
For a column (parameter value BoxLayout.Y_AXIS
), each
component gets its preferred width.
The heights are adjusted according to a formula that incorporates both
preferred and maximum heights.
The component c must be the container that is being laid out.