Java: Flow Layout Manager (Swing)

Posted February 20, 2006 by William_Wilson in Java programming

This tutorial explains how to use the Flow Layout Manager.

Layout Managers are used in the organization of Panels and Frames. The proper layout should be chosen to accommodate frame resizings and use.

The + signs represent empty space.

| Frame Title |▄|▐ |X|
| item1 -> item2 ->++|
| item3 ->… ++++++|
*Items are placed in a flow pattern, one after another, left to right, and top
to bottom. (If the direction chosen is left, other choices are available.)

It is similar to the null layout, but the flow layout arranges the items for you, with a speficied horizontal and vertical gap, all defined within the three constructors allowed in this layout:

public FlowLayout();
-This is the default constructor, with default values supplied. They should be as follows:
align = LEFT
hGap = 0
vGap = 0
*You may want to check that this has stayed the same in updates to the JVM.
public FlowLayout(int align);
-where only the alignment must be specified, and hGap and vGap are supplied as above
public FlowLayout (int align, int hGap, int vGap);
-where you can supply all the variables to your design needs

CODE Example:
import java.awt.*;
import javax.swing.*;
public class FlowLayoutManagerExample extends JFrame {

public FlowLayoutManagerExample (String title) {

Container contentPane = getContentPane();

// Set the layoutManager
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));

// Add components using the layout manager
contentPane.add(new JButton(“one”));
contentPane.add(new JButton(“two”));
contentPane.add(new JButton(“three”));
public static void main(String args[]) {

FlowLayoutManagerExample frame = new FlowLayoutManagerExample(“Example”);
frame.setSize(500, 300);



*NOTE: This frame’s buttons do not actually do anything. This is simply an example of using the Layout Manager.
-Try changing the fram.setResizable to true, and resize the frame.

Questions or Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.