Trail: Creating a GUI with JFC/Swing
Lesson: Laying Out Components Within a Container
How to Use FlowLayout
How to Use FlowLayout
The FlowLayout class provides a very simple layout manager that is used, by default, by JPanels. Here's a picture of an example that uses a flow layout:

A snapshot of FlowLayoutDemo

You can run FlowLayoutDemo using JavaTM Web Start. Its code is in FlowLayoutDemo.java.

FlowLayout puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, FlowLayout uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. You can specify that it stick to the left or right side instead by using a FlowLayout constructor that takes an alignment argument. You can also specify how much vertical or horizontal padding is put around the components.

Below is the code from FlowLayoutDemo.java that creates the FlowLayout and the components it manages.

contentPane.setLayout(new FlowLayout());

contentPane.add(new JButton("Button 1"));
contentPane.add(new JButton("Button 2"));
contentPane.add(new JButton("Button 3"));
contentPane.add(new JButton("Long-Named Button 4"));
contentPane.add(new JButton("5"));

The FlowLayout API

[PENDING: This section will be converted to use API tables, as in the components section.]

The FlowLayout class has three constructors:

public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment,
                  int horizontalGap, int verticalGap)
The alignment argument can be FlowLayout.LEADING, FlowLayout.CENTER, or FlowLayout.TRAILING. When the FlowLayout controls a container with a left-to-right component orientation (the default), LEADING specifies that the components be left-aligned and TRAILING specifies right alignment. The horizontalGap and verticalGap arguments specify the number of pixels to put between components. If you don't specify a gap value, FlowLayout uses 5 for the default gap value.

Examples that Use FlowLayout

The following table lists some of the examples that use flow layout.

Example Where Described Notes
FlowLayoutDemo This page Sets up a content pane to use FlowLayout. If you set the RIGHT_TO_LEFT constant to true and recompile, you can see how FlowLayout handles a container that has a right-to-left component orientation.
CardLayoutDemo How to Use CardLayout To center a component nicely in the top part of a BorderLayout, puts the component in a JPanel that uses a FlowLayout.
ButtonDemo How to Use Buttons, Check Boxes, and Radio Buttons Uses the default FlowLayout of a JPanel.
TextInputDemo How to Use Formatted Text Fields Uses a panel with a right-aligned FlowLayout to present two buttons.

Previous page: How to Use CardLayout
Next page: How to Use GridBagLayout