12.5. GridBagLayout

The GridBagLayout manager is about three times more flexible than any of the other standard layout managers. Unfortunately, GridBagLayout is also about nine times harder to use. The basic idea is that you chop up the window into grids, then you specify for each component which cell to start and end in. You can also specify how objects stretch when there is extra room and alignment within cells.

The basic steps to using GridBagLayout are:

Set the layout, saving a reference to it.

GridBagLayout layout = new GridBagLayout();
setLayout(layout);

Allocate a GridBagConstraints object.

GridBagConstraints constraints =
  new GridBagConstraints();

Set up the GridBagConstraints for component 1.

 constraints.gridx = x1; constraints.gridy ...

Get Core Web Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.