GridBagLayout and Custom Layout Managers in Swing
Laying out real forms in Swing: GridBagLayout cells, spans, weights, fill, anchor and padding, a helper class that tames the constraints, BoxLayout with glue and struts, and writing your own LayoutManager.
kvi5hnuCode Sprout team member13 min readOn this page
Flow, border and grid layouts (Article 93) are enough for toolbars and simple windows, but not for a typical form, where labels line up in one column, fields stretch in another, and a large component spans several rows. The classic tool for this is GridBagLayout, a grid whose rows and columns have different sizes and whose components can span several cells. It has a reputation for being hard, mostly because its constraints object has many fields. With a sketch on paper, a fixed recipe and a tiny helper class, it becomes routine. This article also covers BoxLayout and shows how to write your own layout manager.
Why another layout manager?
Over the years, several designs tried to replace the grid bag:
BoxLayout(Swing 1.2) arranges components in a single row or column. Nested boxes get you far, but each box is laid out on its own, so components in different boxes do not line up with each other.SpringLayout(Java 1.4) connects edges with imaginary springs. It is flexible and so tedious that hardly anyone writes it by hand.GroupLayout(Java 6) describes horizontal and vertical groupings separately. It was designed for GUI builders such as NetBeans' "Matisse" designer, which generate the code.
Outside the JDK, MigLayout and the JGoodies FormLayout are popular for hand-written forms. Still, GridBagLayout is in every JDK, is the most common choice for hand-written layout code, and its concepts (cells, spans, weights, alignment) carry over to the alternatives.
Grid bag basics
Think of a grid bag as a grid layout without its restrictions: rows and columns may differ in size, a component may occupy a rectangle of several cells, and it need not fill its cell. You never tell the layout how many rows and columns there are; it works that out from the constraints.
The procedure:
- Set a
GridBagLayoutas the container's layout manager. - For each component, create a
GridBagConstraintsobject and set its fields. - Add the component with
add(component, constraints).
Here is the plan for a font dialog: labels and combo boxes for face and size, two check boxes, and a sample text area to the right:

Position and span: gridx, gridy, gridwidth, gridheight
gridx and gridy give the column and row of the component's top-left cell, counted from 0. gridwidth and gridheight give how many columns and rows it spans (default 1). The text area in the plan starts at column 2, row 0, and spans one column and four rows: gridx = 2, gridy = 0, gridwidth = 1, gridheight = 4.
Weights: weightx and weighty
Weights decide what happens to extra space when the container is larger than its preferred size. A weight of 0 (the default) means the row or column never grows beyond its preferred size; positive weights share the extra space in proportion. The demo shows four cases for two equal components in a row: with weights 1 and 1 they split the extra space equally; with 1 and 3, the second gets three quarters of it; with 0 and 1, only the second grows; and with 0 and 0 nothing grows, so the components huddle in the middle of the container.
Two things make weights confusing. First, they are properties of rows and columns, but you set them per component; the layout uses the maximum weight in each row or column. To keep a column at a fixed width, every component in it must have weight 0. Second, weights do not determine the relative sizes of columns, only how the extra space is divided.
A practical approach: give everything weight 100, run the program and resize the window. Then set the weight to 0 for every component in a row or column that should not grow. Fine-tuning the other values is rarely worth it.
fill and anchor
If a component should not stretch to fill its whole area, fill says in which directions it does: NONE (the default), HORIZONTAL, VERTICAL or BOTH. Text fields and combo boxes usually get HORIZONTAL; text areas and lists in scroll panes get BOTH; buttons and check boxes stay at NONE.
When the component does not fill its area, anchor places it there: CENTER (the default), or a compass direction (NORTH, NORTHEAST, EAST, ..., NORTHWEST). Better still, use the orientation-aware equivalents (PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_START, LAST_LINE_END), which flip automatically for right-to-left languages. There are also baseline-relative anchors (BASELINE, BASELINE_LEADING, BASELINE_TRAILING) that align a label's text with the text in the neighboring field, which looks noticeably more polished.
Padding: insets, ipadx, ipady
insets adds external padding: blank space between the component and the edges of its area, given as an Insets(top, left, bottom, right). ipadx and ipady add internal padding: they are added to the component's minimum and preferred size, making the component itself bigger. The demo shows both on a 4-pixel component in a 12-pixel cell.
Relative placement
Instead of absolute positions, you may set gridx and gridy to GridBagConstraints.RELATIVE (the default) and add components in reading order: each one goes to the right of the previous one. A gridwidth of GridBagConstraints.REMAINDER marks the last component in a row, which then spans the rest of it. The demo builds three rows this way. It works, but the layout becomes hard to read and fragile to change, so explicit positions are usually better.
A recipe and a helper class
The following recipe works for most grid bag layouts:
- Sketch the layout on paper.
- Draw a grid over it so that each small component sits in one cell and larger ones span several.
- Number the rows and columns from 0 and read off
gridx,gridy,gridwidthandgridheight. - For each component, decide whether it should fill its area horizontally, vertically or both; if not, where it should be anchored.
- Set all weights to 100, then set them to 0 in rows and columns that should keep their size.
- Write the code and double-check every constraint; one wrong value can scramble the layout.
Writing constraints field by field is tedious, so almost everyone uses a small helper class. A subclass of GridBagConstraints with short constructors and setters that return this turns each component into one readable line:
add(faceLabel, new GBC(0, 0).setAnchor(GBC.LINE_END));
add(face, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(4));
add(sample, new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100));
Because it extends GridBagConstraints, the constants are available as GBC.EAST and so on. (The GridBagConstraints constructor with all eleven parameters exists too, but it is meant for code generators; nobody can read eleven positional arguments.) The complete font dialog:
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public final class FontDialogFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final JComboBox<String> face = new JComboBox<>(
new String[] {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG, Font.DIALOG_INPUT});
private final JComboBox<Integer> size = new JComboBox<>(new Integer[] {8, 10, 12, 14, 18, 24, 36, 48});
private final JCheckBox bold = new JCheckBox("Bold");
private final JCheckBox italic = new JCheckBox("Italic");
private final JTextArea sample = new JTextArea("Sphinx of black quartz, judge my vow.", 8, 20);
public FontDialogFrame() {
super("Font");
setLayout(new GridBagLayout());
size.setSelectedItem(18);
sample.setLineWrap(true);
sample.setWrapStyleWord(true);
sample.setEditable(false);
var faceLabel = new JLabel("Face:");
faceLabel.setLabelFor(face);
var sizeLabel = new JLabel("Size:");
sizeLabel.setLabelFor(size);
// column 0 column 1 column 2
// Face: [face v] +-----------+
// Size: [size v] | sample |
// [ ] Bold | (spans |
// [ ] Italic | 4 rows) |
add(faceLabel, new GBC(0, 0).setAnchor(GBC.LINE_END).setInsets(4));
add(face, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(4));
add(sizeLabel, new GBC(0, 1).setAnchor(GBC.LINE_END).setInsets(4));
add(size, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(4));
add(bold, new GBC(0, 2, 2, 1).setWeight(100, 100));
add(italic, new GBC(0, 3, 2, 1).setWeight(100, 100));
add(new JScrollPane(sample), new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100).setInsets(4));
ActionListener update = _ -> updateSample();
face.addActionListener(update);
size.addActionListener(update);
bold.addActionListener(update);
italic.addActionListener(update);
updateSample();
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private void updateSample() {
int style = (bold.isSelected() ? Font.BOLD : 0) | (italic.isSelected() ? Font.ITALIC : 0);
sample.setFont(new Font(face.getItemAt(face.getSelectedIndex()), style,
size.getItemAt(size.getSelectedIndex())));
}
/** GridBagConstraints with short constructors and chainable setters. */
static final class GBC extends GridBagConstraints {
private static final long serialVersionUID = 1L;
GBC(int gridx, int gridy) {
this.gridx = gridx;
this.gridy = gridy;
}
GBC(int gridx, int gridy, int gridwidth, int gridheight) {
this(gridx, gridy);
this.gridwidth = gridwidth;
this.gridheight = gridheight;
}
GBC setAnchor(int anchor) { this.anchor = anchor; return this; }
GBC setFill(int fill) { this.fill = fill; return this; }
GBC setWeight(double weightx, double weighty) { this.weightx = weightx; this.weighty = weighty; return this; }
GBC setInsets(int d) { this.insets = new Insets(d, d, d, d); return this; }
GBC setInsets(int top, int left, int bottom, int right) { this.insets = new Insets(top, left, bottom, right); return this; }
GBC setIpad(int ipadx, int ipady) { this.ipadx = ipadx; this.ipady = ipady; return this; }
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new FontDialogFrame().setVisible(true));
}
}
Note that the labels' column has weight 0 so it keeps its width, the combo boxes stretch horizontally but not vertically, and only the text area grows in both directions. The constraints object can be reused after add, because the layout copies it.
To debug a grid bag, GridBagLayout.getLayoutDimensions() returns the computed column widths and row heights, and getLayoutWeights() the weights the layout derived from the components. The demo prints both.
BoxLayout
For a single row or column, BoxLayout is simpler than a grid bag. The Box class provides containers that use it, along with invisible spacer components:
Box buttons = Box.createHorizontalBox();
buttons.add(Box.createHorizontalGlue()); // pushes the rest to the right
buttons.add(okButton);
buttons.add(Box.createHorizontalStrut(8)); // fixed 8-pixel gap
buttons.add(cancelButton);
A strut is a fixed gap; glue absorbs extra space, so components on its two sides are pushed apart; a rigid area (Box.createRigidArea(dimension)) is a fixed-size block. Unlike the other layout managers, BoxLayout respects the maximum size: a component grows only up to its maximum. Buttons have a maximum equal to their preferred size, while text fields and panels can grow without limit, so a text field in a vertical box becomes taller than you expect. Call setMaximumSize on it to prevent that. In a vertical box, components are aligned according to their alignmentX; mixing values (such as a left-aligned label and a centered button) gives odd results, so set the same alignment for all.
Writing a layout manager
When no standard manager does what you need, write your own. A layout manager implements the LayoutManager interface:
void addLayoutComponent(String name, Component comp)
void removeLayoutComponent(Component comp)
Dimension preferredLayoutSize(Container parent)
Dimension minimumLayoutSize(Container parent)
void layoutContainer(Container parent)
The first two methods are called when components are added and removed; a manager that keeps no information per component leaves them empty. The size methods compute what the container needs, including the container's insets (its border). layoutContainer does the actual work: it calls setBounds on every child. A layout manager never adds or removes components; it only positions and sizes them, and it should skip components whose isVisible() is false. (For brevity the demo's FormLayout below doesn't do this; a production version should test label.isVisible() && field.isVisible() in all three methods and leave out hidden pairs.)
The demo's FormLayout arranges components in pairs: labels right-aligned in a column as wide as the widest label, fields in a second column that takes all remaining width. It is about 50 lines, and it is a layout you would otherwise have to build with a grid bag. Other ideas: a circle layout that places components around an ellipse, a "wrap layout" that fixes the well-known weakness of FlowLayout (its preferred size assumes a single row, so wrapped rows get cut off in a scroll pane), or a layout that hides lower-priority components when space runs out.
There is a second interface, LayoutManager2, which extends LayoutManager with methods for constraints (addLayoutComponent(Component, Object)), maximum size, alignment and invalidateLayout. Implement it if your manager needs constraint objects, as BorderLayout and GridBagLayout do. If you cache computed sizes, clear the cache in invalidateLayout; otherwise the layout will not notice components whose preferred size changed.
The program
The demo uses placeholder components of fixed size and draws each container's layout with one character per pixel, as in Article 93. It builds the font dialog layout, then isolates each constraint: fill, anchor, insets, internal padding, weights and relative placement. It ends with box layouts and the custom FormLayout.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class Solution {
/** A placeholder component with a fixed preferred size, drawn as its letter. */
static class Block extends JComponent {
private static final long serialVersionUID = 1L;
final char letter;
Block(char letter, int w, int h) {
this.letter = letter;
setPreferredSize(new Dimension(w, h));
setMinimumSize(new Dimension(w, h));
}
Block fixed() { setMaximumSize(getPreferredSize()); return this; }
}
/** Short helper for grid bag constraints with chainable setters. */
static class GBC extends GridBagConstraints {
private static final long serialVersionUID = 1L;
GBC(int gridx, int gridy) { this.gridx = gridx; this.gridy = gridy; }
GBC(int gridx, int gridy, int gridwidth, int gridheight) {
this(gridx, gridy);
this.gridwidth = gridwidth;
this.gridheight = gridheight;
}
GBC setAnchor(int anchor) { this.anchor = anchor; return this; }
GBC setFill(int fill) { this.fill = fill; return this; }
GBC setWeight(double wx, double wy) { weightx = wx; weighty = wy; return this; }
GBC setInsets(int d) { insets = new Insets(d, d, d, d); return this; }
GBC setInsets(int top, int left, int bottom, int right) { insets = new Insets(top, left, bottom, right); return this; }
GBC setIpad(int x, int y) { ipadx = x; ipady = y; return this; }
}
/** Two columns: labels right-aligned at their preferred width, fields stretched to fill the rest. */
static class FormLayout implements LayoutManager {
private final int hgap, vgap;
FormLayout(int hgap, int vgap) { this.hgap = hgap; this.vgap = vgap; }
public void addLayoutComponent(String name, Component c) { } // no per-component state
public void removeLayoutComponent(Component c) { }
private int labelWidth(Container parent) {
int w = 0;
for (int i = 0; i < parent.getComponentCount(); i += 2)
w = Math.max(w, parent.getComponent(i).getPreferredSize().width);
return w;
}
private Dimension size(Container parent, boolean preferred) {
int labels = labelWidth(parent), fields = 0, height = 0;
int n = parent.getComponentCount();
for (int i = 0; i + 1 < n; i += 2) {
Dimension l = parent.getComponent(i).getPreferredSize();
Dimension f = preferred ? parent.getComponent(i + 1).getPreferredSize()
: parent.getComponent(i + 1).getMinimumSize();
fields = Math.max(fields, f.width);
height += Math.max(l.height, f.height) + (i > 0 ? vgap : 0);
}
Insets in = parent.getInsets();
return new Dimension(in.left + labels + hgap + fields + in.right, in.top + height + in.bottom);
}
public Dimension preferredLayoutSize(Container parent) { return size(parent, true); }
public Dimension minimumLayoutSize(Container parent) { return size(parent, false); }
public void layoutContainer(Container parent) {
Insets in = parent.getInsets();
int labels = labelWidth(parent);
int fieldX = in.left + labels + hgap;
int fieldW = parent.getWidth() - in.right - fieldX;
int y = in.top;
for (int i = 0; i + 1 < parent.getComponentCount(); i += 2) {
Component label = parent.getComponent(i), field = parent.getComponent(i + 1);
Dimension l = label.getPreferredSize(), f = field.getPreferredSize();
int rowH = Math.max(l.height, f.height);
label.setBounds(in.left + labels - l.width, y, l.width, l.height);
field.setBounds(fieldX, y, fieldW, f.height);
y += rowH + vgap;
}
}
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
EventQueue.invokeAndWait(Solution::run);
}
static void run() {
fontDialog();
fillAndAnchor();
weights();
relative();
boxLayout();
customLayout();
}
static void fontDialog() {
System.out.println("== A font dialog in a grid bag: F/S labels, f/s combo boxes, B/I check boxes, T text ==");
var panel = new JPanel(new GridBagLayout());
panel.add(new Block('F', 5, 1), new GBC(0, 0).setAnchor(GBC.EAST));
panel.add(new Block('f', 8, 1), new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 1, 1, 1));
panel.add(new Block('S', 3, 1), new GBC(0, 1).setAnchor(GBC.EAST));
panel.add(new Block('s', 4, 1), new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 1, 1, 1));
panel.add(new Block('B', 6, 1), new GBC(0, 2, 2, 1).setWeight(100, 100));
panel.add(new Block('I', 6, 1), new GBC(0, 3, 2, 1).setWeight(100, 100));
panel.add(new Block('T', 12, 6), new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100));
Dimension pref = panel.getPreferredSize();
show("preferred size", panel, pref.width, pref.height);
show("enlarged", panel, 40, 10);
var layout = (GridBagLayout) panel.getLayout();
System.out.println("column widths " + Arrays.toString(layout.getLayoutDimensions()[0])
+ ", row heights " + Arrays.toString(layout.getLayoutDimensions()[1]));
System.out.println("column weights " + Arrays.toString(layout.getLayoutWeights()[0]));
}
static void fillAndAnchor() {
System.out.println();
System.out.println("== fill, anchor, insets and ipad in a 12 x 3 cell ==");
Object[][] cases = {
{"fill NONE, anchor CENTER (defaults)", new GBC(0, 0).setWeight(1, 1)},
{"fill HORIZONTAL", new GBC(0, 0).setWeight(1, 1).setFill(GBC.HORIZONTAL)},
{"anchor NORTHEAST", new GBC(0, 0).setWeight(1, 1).setAnchor(GBC.NORTHEAST)},
{"fill BOTH, insets 1", new GBC(0, 0).setWeight(1, 1).setFill(GBC.BOTH).setInsets(1)},
{"ipadx 4 (internal padding)", new GBC(0, 0).setWeight(1, 1).setIpad(4, 0)},
};
for (Object[] c : cases) {
var panel = new JPanel(new GridBagLayout());
panel.add(new Block('X', 4, 1), (GBC) c[1]);
show((String) c[0], panel, 12, 3);
}
}
static void weights() {
System.out.println();
System.out.println("== weights: who gets the extra width? ==");
double[][] w = {{0, 0}, {1, 1}, {1, 3}, {0, 1}};
for (double[] pair : w) {
var panel = new JPanel(new GridBagLayout());
panel.add(new Block('A', 4, 1), new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(pair[0], 0));
panel.add(new Block('B', 4, 1), new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(pair[1], 0));
show("weightx " + pair[0] + " and " + pair[1], panel, 24, 1);
}
}
static void relative() {
System.out.println();
System.out.println("== RELATIVE positions and REMAINDER ==");
var panel = new JPanel(new GridBagLayout());
var c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
panel.add(new Block('a', 4, 1), c);
panel.add(new Block('b', 4, 1), c);
c.gridwidth = GridBagConstraints.REMAINDER; // last one in its row
panel.add(new Block('c', 4, 1), c);
c.gridwidth = 1;
panel.add(new Block('d', 4, 1), c);
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(new Block('e', 4, 1), c); // spans the rest of row 1
panel.add(new Block('f', 4, 1), c); // a full row of its own
show("added in reading order", panel, 15, 3);
}
static void boxLayout() {
System.out.println();
System.out.println("== BoxLayout with glue and struts ==");
Box row = Box.createHorizontalBox();
row.add(new Block('H', 4, 1).fixed());
row.add(Box.createHorizontalGlue()); // absorbs extra space
row.add(new Block('O', 4, 1).fixed());
row.add(Box.createHorizontalStrut(2)); // fixed gap
row.add(new Block('C', 6, 1).fixed());
show("horizontal box", row, 24, 1);
Box col = Box.createVerticalBox();
col.add(new Block('1', 10, 1).fixed());
col.add(Box.createVerticalStrut(1));
col.add(new Block('2', 24, 2)); // no maximum size: stretches
col.add(new Block('3', 6, 1).fixed());
show("vertical box", col, 16, 5);
}
static void customLayout() {
System.out.println();
System.out.println("== A custom LayoutManager: label/field form ==");
var form = new JPanel(new FormLayout(1, 1));
form.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
form.add(new Block('n', 5, 1));
form.add(new Block('N', 8, 1));
form.add(new Block('e', 7, 1));
form.add(new Block('E', 10, 1));
form.add(new Block('c', 3, 1));
form.add(new Block('C', 6, 3));
Dimension pref = form.getPreferredSize();
show("preferred size", form, pref.width, pref.height);
show("wider: fields stretch, labels stay right-aligned", form, 30, pref.height);
}
static void show(String title, Container c, int w, int h) {
c.setSize(w, h);
layoutTree(c);
char[][] grid = new char[h][w];
for (char[] row : grid) Arrays.fill(row, '.');
paintTree(c, 0, 0, grid);
System.out.println(title + " (" + w + " x " + h + ")");
for (char[] row : grid) System.out.println(" " + new String(row));
}
static void layoutTree(Container c) {
c.doLayout();
for (Component child : c.getComponents()) if (child instanceof Container k) layoutTree(k);
}
static void paintTree(Container c, int ox, int oy, char[][] grid) {
for (Component child : c.getComponents()) {
Rectangle r = child.getBounds();
if (child instanceof Block b) {
for (int y = r.y; y < r.y + r.height; y++)
for (int x = r.x; x < r.x + r.width; x++) {
int gx = ox + x, gy = oy + y;
if (gy >= 0 && gy < grid.length && gx >= 0 && gx < grid[0].length) grid[gy][gx] = b.letter;
}
} else if (child instanceof Container k) {
paintTree(k, ox + r.x, oy + r.y, grid);
}
}
}
}
== A font dialog in a grid bag: F/S labels, f/s combo boxes, B/I check boxes, T text ==
preferred size (27 x 6)
FFFFF.ffffffff.TTTTTTTTTTTT
...............TTTTTTTTTTTT
..SSS.ssssssss.TTTTTTTTTTTT
...............TTTTTTTTTTTT
....BBBBBB.....TTTTTTTTTTTT
....IIIIII.....TTTTTTTTTTTT
enlarged (40 x 10)
FFFFF.ffffffffffffff.TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
..SSS.ssssssssssssss.TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
.......BBBBBB........TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
.......IIIIII........TTTTTTTTTTTTTTTTTT.
.....................TTTTTTTTTTTTTTTTTT.
column widths [5, 16, 18], row heights [2, 2, 3, 3]
column weights [0.0, 100.0, 100.0]
== fill, anchor, insets and ipad in a 12 x 3 cell ==
fill NONE, anchor CENTER (defaults) (12 x 3)
............
....XXXX....
............
fill HORIZONTAL (12 x 3)
............
XXXXXXXXXXXX
............
anchor NORTHEAST (12 x 3)
........XXXX
............
............
fill BOTH, insets 1 (12 x 3)
............
.XXXXXXXXXX.
............
ipadx 4 (internal padding) (12 x 3)
............
..XXXXXXXX..
............
== weights: who gets the extra width? ==
weightx 0.0 and 0.0 (24 x 1)
........AAAABBBB........
weightx 1.0 and 1.0 (24 x 1)
AAAAAAAAAAAABBBBBBBBBBBB
weightx 1.0 and 3.0 (24 x 1)
AAAAAAAABBBBBBBBBBBBBBBB
weightx 0.0 and 1.0 (24 x 1)
AAAABBBBBBBBBBBBBBBBBBBB
== RELATIVE positions and REMAINDER ==
added in reading order (15 x 3)
aaaaabbbbbccccc
dddddeeeeeeeeee
fffffffffffffff
== BoxLayout with glue and struts ==
horizontal box (24 x 1)
HHHH........OOOO..CCCCCC
vertical box (16 x 5)
...1111111111...
................
2222222222222222
2222222222222222
.....333333.....
== A custom LayoutManager: label/field form ==
preferred size (20 x 9)
....................
...nnnnn.NNNNNNNNNN.
....................
.eeeeeee.EEEEEEEEEE.
....................
.....ccc.CCCCCCCCCC.
.........CCCCCCCCCC.
.........CCCCCCCCCC.
....................
wider: fields stretch, labels stay right-aligned (30 x 9)
..............................
...nnnnn.NNNNNNNNNNNNNNNNNNNN.
..............................
.eeeeeee.EEEEEEEEEEEEEEEEEEEE.
..............................
.....ccc.CCCCCCCCCCCCCCCCCCCC.
.........CCCCCCCCCCCCCCCCCCCC.
.........CCCCCCCCCCCCCCCCCCCC.
..............................
Points to notice:
- In the enlarged font dialog, column 0 (weight 0) kept its width of 5; columns 1 and 2 shared the extra space. Integer rounding left one column of pixels unused at the right.
- The check boxes spanned columns 0 and 1 and were centered in that area (
fillNONE,anchorCENTER), while the combo boxes filled their cells horizontally. ipadx 4made the component 8 pixels wide; insets of 1 shrank the filled area on every side.- In the vertical box, the blocks with a maximum size kept their width and were centered; block 2, without a maximum size, stretched to the full width.
Common questions
My GridBagLayout puts everything in the center. Why?
All weights are 0, so the grid keeps its preferred size and is centered in the container. Give at least one column a positive weightx and one row a positive weighty where extra space should go.
Why does my text field collapse to a tiny width?
When the container is smaller than the preferred size, GridBagLayout falls back to minimum sizes, and a text field's minimum can be very small. Give the window enough room (pack()), or set a minimum size on the field.
GridBagLayout, GroupLayout or MigLayout?
GridBagLayout for hand-written code without dependencies. GroupLayout is meant for GUI builders and is verbose by hand. MigLayout gives the most readable hand-written forms, at the cost of a dependency.
How do I make two buttons the same width?
Put them into a panel with GridLayout(1, 0, gap, 0), which makes all cells equal, then put that panel into the outer layout. In GroupLayout, linkSize does the same.
When should I write my own layout manager?
When the same non-standard arrangement recurs (a form with label/field pairs, a wrapping flow, a circle) and expressing it with constraints is painful. Keep it stateless, honor insets and invisible components, and implement LayoutManager2 if it needs constraints.
API reference
| Class / method | Purpose |
|---|---|
GridBagLayout, getLayoutDimensions, getLayoutWeights | Grid bag layout; inspect computed sizes and weights. |
GridBagConstraints.gridx, gridy, gridwidth, gridheight | Cell position and span; RELATIVE, REMAINDER. |
GridBagConstraints.weightx, weighty | Share of extra space; the maximum per row or column counts. |
GridBagConstraints.fill | NONE, HORIZONTAL, VERTICAL, BOTH. |
GridBagConstraints.anchor | CENTER, compass points, LINE_START, LINE_END, PAGE_START, PAGE_END, FIRST_LINE_START, ..., BASELINE. |
GridBagConstraints.insets, ipadx, ipady | External and internal padding. |
Box.createHorizontalBox, createVerticalBox, createHorizontalGlue, createVerticalGlue, createHorizontalStrut, createVerticalStrut, createRigidArea | Box layout and spacers. |
BoxLayout(container, axis); JComponent.setMaximumSize, setAlignmentX, setAlignmentY | Box layout control. |
LayoutManager.addLayoutComponent, removeLayoutComponent, preferredLayoutSize, minimumLayoutSize, layoutContainer | Custom layout manager. |
LayoutManager2.addLayoutComponent(comp, constraints), maximumLayoutSize, getLayoutAlignmentX/Y, invalidateLayout | Layout managers with constraints. |
Container.getInsets, Component.setBounds, getPreferredSize, isVisible | Used inside layout managers. |
Summary
GridBagLayoutplaces components in a grid with variable row and column sizes; components may span cells and need not fill them.- Position and span come from
gridx,gridy,gridwidth,gridheight;weightx/weightydistribute extra space (per row or column, using the maximum);fillandanchorplace a component within its area;insetsandipadx/ipadyadd padding. - Sketch the grid first, read off the values, set weights to 100 and zero out fixed rows and columns, and use a helper class with chainable setters.
BoxLayouthandles single rows and columns with glue, struts and rigid areas, and respects maximum sizes.- A custom
LayoutManagercomputes preferred and minimum sizes and callssetBoundson each child inlayoutContainer; implementLayoutManager2for constraints.
Practice Questions
1. In a grid bag, one label in column 0 has weightx 0 and a text field below it, also in column 0, has weightx 100. Does column 0 grow when the window is widened?
Yes. The layout assigns each column the maximum weight of the components in it, which is 100 here. To keep a column at a fixed width, every component in that column must have a weight of 0.
2. All components in a grid bag have weightx = 0 and weighty = 0. What happens when the user enlarges the window?
No row or column takes any extra space, so the whole grid stays at its preferred size and sits in the center of the container, surrounded by empty space. Give positive weights to the rows and columns that should grow.
3. What is the difference between insets and ipadx?
insets is external padding: empty space between the component and the edges of its display area; the component itself does not get bigger. ipadx (and ipady) is internal padding: it is added to the component's minimum and preferred width (and height), so the component itself becomes larger.
4. A text field in a vertical Box becomes very tall when the window is enlarged, while the buttons in the same box keep their size. Why, and how do you fix it?
BoxLayout lets components grow up to their maximum size. Buttons report a maximum equal to their preferred size, but a text field's maximum height is unbounded, so the field takes the extra space. Limit it, for example with field.setMaximumSize(new Dimension(Integer.MAX_VALUE, field.getPreferredSize().height)), or add vertical glue to absorb the space.
5. What must the layoutContainer method of a custom layout manager do, and what must it not do?
It must compute a position and size for each (visible) child component, taking the container's current size and insets into account, and call setBounds on each child. It must not add or remove components or change the container's own size; that is the job of the container and its parent's layout manager. The preferred and minimum size methods must be consistent with what layoutContainer does.
Previous: Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
Next: Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser
Related reading
- Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
- Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
- Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
- Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout
- The Java Preferences API: Storing User Settings

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.