Java Notes

FlowLayout

java.awt.FlowLayout arranges components from left-to-right and top-to-bottom, centering components horizontally with a five pixel gap between them. When a container size is changed (eg, when a window is resized), FlowLayout recomputes new positions for all components subject to these constraints.

Use FlowLayout because it's quick and easy. It's a good first choice when using iterative development. I often start with a FlowLayout in an early iteration then switch to a better layout, if necessary, on a later iteration.

Example


The window above is the default size after packing the FlowLayout. The window on the right shows the same window after it has been resized by dragging the lower-right corner, resulting in components flowing down onto other lines.

Source code for example

Here is the relevant part of the source code for the above example.

// Note: a real program would add listeners to the buttons.
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("2"));
content.add(new JButton("This is button three"));
content.add(new JButton("four"));

Constructors

Typically the constructor is called in the call to the container's setLayout method (see example code). The parameterless FlowLayout() constructor is probably most common, but there are some good places to use the alignment.

new FlowLayout()         // default is centered with 5 pixel gaps
new FlowLayout(int align)
new FlowLayout(int align, int hgap, int vgap)

Alignment

align is one of FlowLayout.LEFT, FlowLayout.CENTER (the default), or FlowLayout.RIGHT. You might want to use the RIGHT aligment when building a dialog that puts the OK and Cancel buttons at the lower right.

Spacing

The default spacing is good for most purposes and is rarely changed. hgap is the size in pixels of the horizontal gap (distance) between components, and vgap is the vertical gap.

Typical uses

Problem

FlowLayout makes components as small as possible, and does not use their preferred size. This can show up when you define a JPanel for drawing. Typically you will set a preferred size, but the panel may "disappear" in a FlowLayout because it was set to its minimum size (0).