Leepoint Java Reference Notes on the Java language and its standard library.

Null layout, and why not to use it

Setting coordinates by hand. Tempting, and wrong in four specific ways.

Set the layout manager to null and position everything yourself:

panel.setLayout(null);
JButton b = new JButton("OK");
b.setBounds(10, 10, 80, 25);
panel.add(b);

setBounds is x, y, width, height, in pixels, relative to the container. Without a layout manager, a component that has not been given bounds has zero size and does not appear — the usual first symptom.

Why it is tempting

It is the only approach where the result is exactly what you specified. Layout managers have opinions, and fighting one to get a control three pixels to the left is genuinely frustrating.

The four failures

Resizing. Nothing moves. Enlarge the window and everything stays in the top-left with grey space around it. Shrink it and components are clipped.

Fonts. Sizes differ between platforms and with the user’s accessibility settings. A button sized for its label on your machine truncates the text on another. This is the one that hurts most, because it is invisible until someone else runs it.

Look and feel. Swap the look and feel and every component’s preferred size changes. A hand-positioned layout tuned for one becomes overlapping boxes in another.

Screen scaling. On a high-DPI display, hard-coded pixels are the wrong physical size. Everything ends up too small or misaligned.

Between them, these mean a null layout is correct on exactly one machine: the one it was built on.

What to use instead

  • BorderLayout — five regions. Fine for a window with a toolbar, a status bar and content.
  • FlowLayout — a row that wraps. Good for a button bar.
  • GridLayout — equal cells.
  • BoxLayout — one row or column, with control over spacing.
  • GridBagLayout — anything, verbosely.
  • GroupLayout — what the form designers generate; awkward by hand.

Nesting simple managers usually beats one complex one. A BorderLayout containing a BoxLayout is easier to read and change than a single GridBagLayout with a dozen constraint objects.

Where it is acceptable

A drawing surface where you are positioning things by genuine coordinates — a diagram editor, a game board, a chart with movable markers. There the coordinates are the model, so a layout manager has nothing to contribute.

Even then, handle the resize yourself rather than ignoring it.