The Java TM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search

Trail: Creating a GUI with JFC/Swing
Lesson: Laying Out Components Within a Container

## How to Use FlowLayout

> The `FlowLayout` class provides a very simple layout manager that is used, by default, by `JPanel`s. Here's an applet that shows a flow layout in action:

> This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.

> `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. Within each row, components are centered (the default), left-aligned, or right-aligned as specified when the `FlowLayout` is created.

> Below is the code that creates the `FlowLayout` and the components it manages. You can find the whole program in `FlowWindow.java`. The program runs either within an applet (with the help of `AppletButton`) or as an application.

> >     Container contentPane = getContentPane();
> >     contentPane.setLayout(new FlowLayout());

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

### The FlowLayout API

> The `FlowLayout` class has three constructors:

> >     public FlowLayout()
> >     public FlowLayout(int alignment)
> >     public FlowLayout(int alignment,
> >                       int horizontalGap, int verticalGap)

> The `alignment` argument must have the value `FlowLayout.LEFT`, `FlowLayout.CENTER`, or `FlowLayout.RIGHT`. 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
> --- | --- | ---
> `FlowWindow` | This page | Sets up a content pane to use `FlowLayout`.
> `ButtonDemo` | How to Use Buttons, Check Boxes, and Radio Buttons | Uses the default `FlowLayout` of a `JPanel`.

| Start of Tutorial > Start of Trail > Start of Lesson | Search