FlowLayout: Simple Left-to-Right Layout
FlowLayout arranges components in a row, one after another, wrapping to new lines when there is not enough horizontal space.
Example: Five buttons in a FlowLayout
This example uses FlowLayout.CENTER with horizontal and vertical gaps of 10 pixels between buttons.
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
MyFrame() {
setTitle("Layouts - FLowLayout");
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
/*
Here FlowLayout can be called as:
1) FLowlayout(): General flow;
2)FlowLayout(int allign): specific allignment of items
allignment can be done in two ways:
0 or LEFT
1 or CENTER
2 or RIGHT
3 or LEADING
4 or TRALING
FlowLayout(1) or FlowLayout(FlowLayout.CENTER) is same
3) FlowLayout(int align, int hgap, int vgap):
giving specific horizontal gap and Vertical gap between items
*/
JButton b1 = new JButton("Button 01");
JButton b2 = new JButton("Button 02");
JButton b3 = new JButton("Button 03");
JButton b4 = new JButton("Button 04");
JButton b5 = new JButton("Button 05");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class FlowLayoutDemo {
public static void main(String arr[]) {
new MyFrame();
}
}What is FlowLayout?
FlowLayout is the simplest layout manager. Components are placed in a row from left to right, then wrap to the next line.
- Good for small toolbars or simple test programs.
- Supports alignment: LEFT, CENTER, RIGHT, LEADING, TRAILING.
- Can set horizontal and vertical gaps between components.
Line-by-line: Understanding the FlowLayout code
We focus on how the layout is set and how components are added.
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
Uses FlowLayout with CENTER alignment and 10-pixel gaps horizontally and vertically between components.
JButton b1 = new JButton("Button 01"); ...
add(b1); add(b2); add(b3); add(b4); add(b5);
Creates five buttons and adds them to the frame. FlowLayout decides where they appear.
When to use FlowLayout
Use FlowLayout for quick demos, simple forms, or when you only have a few components in a row. For more control, use GridLayout or other managers.