Layout Managers are a collection of standard Java based layout managers for AWT & Swing components. The managers handle the logic of how to size, position & align Components within a Container, and set the orientation of the container so that it is appropriate for the locale in which the program is running.
LayoutManager
is the Java interface for classes that know how to layout the contents of Container
. The typical containers include JPanel
for Swing and Panel
for AWT but many others (like Window
) are possible.
The layout manager lays out container components following rules that are different for each implementation. For instance, GridLayout
arranges components in a table-like way while BorderLayout
places one into center and up to four others at each edge.
While layout managers often call getPreferredSize
on the component to know how much space it would need, the size hints are also regularly ignored. E.G. in GridLayout
all components become the size of the largest width and height, in BorderLayout
the CENTER
component will be stretched to the available space, the top/bottom will be stretched in width and the line start/end will be stretched in height).
Layouts are typically combined in order to achieve complex GUIs. E.G. as seen in the Nested Layout Example.
If the layout manager of some particular component is set to null
, components can be positioned in arbitrary way by setting they bounds manually. This causes many problems, & the first step in fixing those problems is typically to 'set a layout'.
Existing Layout Managers
AWT
BorderLayout
. Provides aCENTER
& 4 borders in which to place components.CardLayout
good for swapping many components or views in a single parent container.FlowLayout
easiest to use, puts components one after another, left-right, top-to-bottom. Typically only suited to single rows of components.GridBagLayout
can do some simple tasks easily (like 'center at preferred size') yet also allows complex layouts.GridLayout
provides a WxH grid of component spaces, each the same size.
Swing
BoxLayout
provides a 'box' like construct for adding components in a row or column.GroupLayout
is powerful, allowing alignment across components and component groups, but is generally considered to be a layout for use by an IDE.OverlayLayout
allows components to be stacked.ScrollPaneLayout
Used internally by other Swing components.SpringLayout
is a way of layoun out components with white space allowing alignment along component edges.ViewportLayout
Used internally by other Swing components.
3rd party
MigLayout
is highly regarded.FormLayout
part of the JGoodies FormsTableLayout
- An Alternative toGridBagLayout