Java Swings/Swing Layouts

The layout of components is dictated by the layout manager used. There are 7 layout managers built into Java. Most UIs are built using some combination of them, typically by nesting layout managers. The most commonly used layouts are FlowLayout, BorderLayout and BoxLayout.

BorderLayout

 * Used to arrange components around a center panel.
 * Sizes components to use all available space for their region.
 * North / South components will be as tall as their preferred height and as wide as the width of the component they're in.
 * East / West components will be as wide as their preferred width and as tall as the height of the component they're in minus the preferred heights of the North and South components.
 * Center will use all remaining space in the component after the North / South / East / West components have been sized.

FlowLayout

 * Used to arrange components in a straight horizontal line.
 * If there is not enough space for all the components to fit, they'll be moved to the next line.
 * Components are set at their preferred sizes.

BoxLayout

 * Used to arrange components vertically or horizontally.  is essentially a replacement for   that is more powerful if thats what you're going for. However with great power comes great responsibility... or something like that. The trade off for having more power is you have to do a bit more work, but you can get things to look closer to what you really want. To demonstrate we'll go through several examples.

s come in two basic flavors. Vertical or horizontal. These are represented by the constants,  ,  ,. X/Y_AXIS specify to always layout the components along the X or Y axis of the container. The components are then arranged left to right (X_AXIS) or top to bottom (Y_AXIS). LINE/PAGE_AXIS will do exactly the same thing as X/Y_AXIS assuming the  field of the parent container is left to right oriented. If not, LINE_AXIS will add components from right to left, and PAGE_AXIS will by default align components on the right side of the panel. If you are planning to support locale specific layouts, PAGE_AXIS is the one for you.

Talking about alignments is fun, but lets see a demo. The below demo will create a main window which will allow you to create child windows laid out with the proper alignments.

CardLayout

 * Used to show one component at a time from a set of components. It is like a deck of flash cards, where you show one of the cards at a time, hence the name. You can quickly change which component is shown at any time, e.g., when the user clicks a button.

GridLayout

 * Used to arrange components in an evenly spaced grid.