Skip to content
Tutorials Center
My learning

Topics

Lesson 147 of 201 ยท Desktop GUI

Swing Layout Managers

Go beyond the basics with Swing layout managers - BoxLayout alignment and glue, GridBagLayout constraints and weights, CardLayout decks and when to nest panels.

Swing Basics introduced BorderLayout, FlowLayout and GridLayout. They are enough for simple windows, but real forms and tool windows need more control: a column of buttons that line up on the left, a form where only the text fields stretch, a wizard that shows one page at a time. Swing's remaining layout managers solve exactly those problems, and this lesson walks through the three you will meet most often: BoxLayout, GridBagLayout and CardLayout.

Our server has no screen, so the complete window programs here are read-only. The runnable examples use Swing's real layout managers on plain panels with fixed sizes and print the rectangles they compute, which is exactly what the layout engine does on a real screen.

Why panels instead of buttons? Buttons and text fields measure their text with fonts, and our headless server has none. In your own program you would use real components. The layout code is identical.

How a layout manager decides

Every layout manager asks each child three questions: what is your minimum, preferred and maximum size? Then it combines the answers with the container's current size. Different managers use the answers differently:

Manager Uses preferred size Uses min/max Best for
FlowLayout Yes, always No A row of buttons
BorderLayout Along one axis per region No A window's overall frame
GridLayout No (all cells equal) No Calculators, boards
BoxLayout Yes Yes (max stops growth) Rows and columns of controls
GridBagLayout Yes Yes Forms and irregular grids
CardLayout No (each card fills the area) No Wizards, tabs you draw yourself

Each manager also decides how big the container itself wants to be: container.getPreferredSize() and frame.pack() use that answer to size a window around its contents.

BoxLayout: a single row or column

BoxLayout stacks components along one axis: BoxLayout.X_AXIS for a row, BoxLayout.Y_AXIS for a column. Unlike FlowLayout, it never wraps. Unlike GridLayout, every child keeps its own preferred size. The constructor takes the container it will manage:

Java
JPanel column = new JPanel();
column.setLayout(new BoxLayout(column, BoxLayout.Y_AXIS));

Along the main axis, children are placed one after another. On the other axis, each child's alignment (setAlignmentX in a column, setAlignmentY in a row) decides where it sits. The default is 0.5, the center, and the constants Component.LEFT_ALIGNMENT (0.0) and RIGHT_ALIGNMENT (1.0) give left and right. All children in the same container should agree: if one says left and another says center, they will not line up the way you expect.

javax.swing.Box provides the invisible spacers:

Call Effect
Box.createRigidArea(new Dimension(w, h)) A fixed gap
Box.createVerticalStrut(h) / createHorizontalStrut(w) A fixed gap on one axis
Box.createVerticalGlue() / createHorizontalGlue() A gap that absorbs all spare space
Box.createGlue() Glue for either axis

Glue is what pushes things to the far end: put it before a component and that component sticks to the end; put it between two components and they move apart. Run this example, which lays out a column in a 200-pixel-tall panel, changes the alignment, then makes the panel taller:

Java BoxLayout, struts and glue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the first layout the three boxes are centered (x = 60, 40, 70 around the 200-pixel midline). After the alignment change they all start at x = 0. The vertical gap between open and save stays 10 pixels in every layout, while the glue between save and quit stretches from 100 to 200 pixels, so quit moves from y = 170 to y = 270. That is the typical use: a toolbar-like column with a few actions at the top and one at the very bottom.

A subtle point: BoxLayout also respects maximum sizes. A JTextField in a vertical box would normally stretch to the full width because its maximum width is huge, which is usually what you want for fields but not for buttons. If a button stretches unexpectedly, call setMaximumSize(button.getPreferredSize()).

GridBagLayout: the flexible grid

GridBagLayout places components in a grid of rows and columns whose sizes depend on what is inside them, so unlike GridLayout the cells are not all equal. A component can span several cells, stay small inside a big cell, or stretch to fill it. The price is that every component is added together with a GridBagConstraints object that describes how it should behave. The fields you use most:

Field Meaning
gridx, gridy Column and row of the top-left cell (starting at 0)
gridwidth, gridheight How many columns/rows to span (default 1)
weightx, weighty How spare space is shared out; 0 means "do not grow"
fill NONE, HORIZONTAL, VERTICAL or BOTH: stretch the component inside its cell
anchor Where a component sits if it does not fill its cell: LINE_START, LINE_END, CENTER, PAGE_START...
insets Margin around the component
ipadx, ipady Extra padding added to the component's size

The weights matter most. If every weight in a column is 0, that column keeps its natural width and the whole grid is centered in the container with leftover space around it. Give one column weightx = 1.0 and it absorbs all the extra width; give two columns weights 1.0 and 2.0 and they split it one to two. For a typical form: labels get weight 0 and text fields get weight 1, so only the fields grow when the window is resized.

Here is a small form (label, field, and an OK button spanning both columns). Watch how only the field column grows between 300 and 500 pixels:

Java GridBagLayout weights and spans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The preferred size, 176 x 68, is the sum of the content plus the insets. At 300 pixels wide the field is 224 wide and at 500 it is 424: the extra 200 pixels all went to column 1, because it holds the only non-zero weight. The label stays at 60 pixels, and the OK button stays right-aligned by its anchor. Both rows sit in the vertical middle of the container because no row has a weighty; give the last row a weighty = 1.0 if you want the form pinned to the top.

You can see the same constraints in a complete, real window. This program is read-only here; run it locally with java LoginForm.java:

Java
import java.awt.*;
import javax.swing.*;

public class LoginForm {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JPanel form = new JPanel(new GridBagLayout());
            form.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
            var c = new GridBagConstraints();
            c.insets = new Insets(4, 4, 4, 4);

            c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_END;
            form.add(new JLabel("User name:"), c);
            c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1;
            form.add(new JTextField(18), c);

            c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; c.weightx = 0;
            form.add(new JLabel("Password:"), c);
            c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1;
            form.add(new JPasswordField(18), c);

            c.gridx = 1; c.gridy = 2; c.fill = GridBagConstraints.NONE; c.weightx = 0;
            c.anchor = GridBagConstraints.LINE_END;
            form.add(new JButton("Sign in"), c);

            JFrame frame = new JFrame("Sign in");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(form);
            frame.pack();                       // ask the layout how big the window must be
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Notice that one GridBagConstraints object is reused: add copies the values, so you can change fields and add the next component. The danger is the opposite one: forgetting to reset a field such as fill or weightx, so the next component inherits it by accident. Many programmers wrap this in a helper method (like at(...) in the runnable example) that builds a fresh constraints object for each call.

CardLayout: one visible component at a time

CardLayout stacks components like a deck of cards, each as large as the container, and shows exactly one. You add each card with a name, then flip through them:

Method Effect
show(container, "name") Show the card with that name
next(container) / previous(container) Move one card forward/back, wrapping around
first(container) / last(container) Jump to the ends

It is the right tool for wizards, a settings window with several pages selected from a list, or a screen switcher. Here the cards are plain panels, and we check which one is visible after each call:

Java Flipping through a CardLayout deck

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All three cards have the same bounds (300 x 200); only the visible flag differs. A wizard usually wires its Next and Back buttons to cards.next(deck) and cards.previous(deck). The deck's preferred size is the size of the largest card, so the window does not jump around while you page through it.

For a tab bar that the user clicks, you rarely need CardLayout yourself: JTabbedPane already manages the cards and draws the tabs.

Combining managers

You almost never use one layout manager for a whole window. The standard recipe is to nest panels, each with the manager that suits its job:

  • The frame's content pane uses BorderLayout.
  • NORTH holds a toolbar panel with FlowLayout or BoxLayout (X axis).
  • CENTER holds a form panel with GridBagLayout, or a CardLayout deck of such forms.
  • SOUTH holds a button row: a BoxLayout on the X axis with glue first, so the buttons stay on the right.

Nesting costs little, and it keeps each piece simple. A panel with six rows of GridBagLayout constraints is easier to reason about than one giant grid that also contains the toolbar.

Pitfalls and good habits

  • Avoid setLayout(null). Absolute positioning with setBounds looks fine on your machine and breaks with other fonts, other platforms, other languages and high-DPI screens.
  • Call pack() on a frame after adding components, so it gets the size its layout asks for, instead of guessing pixel sizes.
  • Let components report their own size. Prefer JTextField(20) (20 columns) over setPreferredSize(new Dimension(...)), because a column count adapts to the font. Fixed sizes belong in demos like ours.
  • Do not mix managers in one container, and do not add the same component to two containers: a component has one parent.
  • After adding or removing components at run time, call revalidate() and then repaint() on the container so the layout runs again.
  • Other options exist. GroupLayout is what many GUI designers (such as the NetBeans builder) generate. SpringLayout lets you attach edges to each other. Third-party libraries such as MigLayout shorten complex forms considerably. The ones in this lesson ship with every JDK and are enough for most programs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A vertical BoxLayout column holds several buttons, but they are centered instead of left-aligned. What is the usual fix?

    BoxLayout aligns children across the main axis by each child's alignment value, which defaults to 0.5 (center). Set the same alignment on all children so they line up.
  2. 2. In a GridBagLayout form, which setting makes the text field column grow when the window is resized while the label column keeps its size?

    Spare width is shared according to the weights. Only columns with a positive weight grow, so give the field column a weight and leave the labels at 0 (and use fill = HORIZONTAL so the field fills its cell).
  3. 3. What does Box.createVerticalGlue() do inside a vertical BoxLayout?

    Glue is an invisible component with no maximum size limit. It takes whatever space is left over, so components placed after it end up at the bottom.
  4. 4. Which layout manager would you use for a wizard that shows one page at a time?

    CardLayout stacks its children and shows exactly one, and next(), previous() and show() switch between them.
  5. 5. Why is setLayout(null) with setBounds discouraged?

    Layout managers recompute positions from the real preferred sizes and the available space. Absolute positions cannot adapt.

Summary

  • A layout manager positions children from their minimum, preferred and maximum sizes and the container's size; pack() sizes a window from that.
  • BoxLayout makes a row or column; use setAlignmentX/Y consistently and Box struts and glue for gaps and to push components to an end.
  • GridBagLayout builds forms and irregular grids from GridBagConstraints: cell position, span, weightx/weighty for stretching, fill, anchor, insets.
  • CardLayout shows one named component at a time; use show, next, previous for wizards, or JTabbedPane for clickable tabs.
  • Nest panels with different managers instead of forcing one manager to do everything, and avoid null layouts.
  • After changing a container at run time, call revalidate() and repaint().

Next: Swing Events and a Small App, where you'll make those windows respond to clicks and typing.