AWT Layout Managers

Site Admin · 11 Sep 2026 · 1 views

How Layout Managers Work

A layout manager positions and resizes components inside a container automatically, so the GUI survives window resizing. Set one with setLayout(manager).

FlowLayout

Places components left to right, wrapping when the edge is reached:

setLayout(new FlowLayout());
add(new Button("One"));
add(new Button("Two"));

FlowLayout demo

BorderLayout

Five regions: NORTH, SOUTH, EAST, WEST, CENTER. The default for Frame.

setLayout(new BorderLayout());
add(new Button("Top"), BorderLayout.NORTH);
add(new Button("Center"), BorderLayout.CENTER);

BorderLayout regions

BorderLayout demo output

GridLayout and CardLayout

// Equal cells in a grid
setLayout(new GridLayout(2, 3));

// Stacked cards, one visible at a time
setLayout(new CardLayout());

GridLayout demo

CardLayout demo

GridBagLayout

The most flexible manager: components specify grid cells, weights and fills with GridBagConstraints.

GridBagLayout gb = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gb);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0; c.gridy = 0;
add(new Button("A"), c);

GridBagLayout demo

Key Points

  • Layout managers resize components when the window changes size.
  • Frame defaults to BorderLayout; Panel defaults to FlowLayout.
  • GridBagLayout gives precise control for complex forms.
Share this post:

Comments (0)

Please login or register to comment.