What are the Layout Managers in Java

The Layout Managers in Java are classes responsible for how the components will be placed inside the container. There are different types of layout managers. In this tutorial, we will only discuss some of the most commonly used layout managers, the Flow Layout, Border Layout, Grid Layout, Card Layout, and Grid Bag Layout. We will start first with the Flow Layout.

Layout Managers in Java: The Flow Layout

This is the default layout manager. The Flow Layout layout its component based on the order when they are added to the container. It starts from the top to bottom, left to right. For example, if I have 3 JButtons, and add first button1, button2 and lastly the button3, the first that will be added and layout will be button1 and it will be on the top left of the container. If there is still enough room, then button2 will be added also on the top portion, else, it will be below button1.

We have used flow layout manager from the last tutorial. Let’s take another example here.

package com.javapointers.javase;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FlowLayoutTest {
    JFrame frame;
    JPanel pane1, pane2;
    JButton button;
    public FlowLayoutTest() {
        frame = new JFrame("Flow Layout Test");
        frame.setSize(500, 400);
        pane1= new JPanel();
        pane1.setPreferredSize(new Dimension(300, 100));
        pane2 = new JPanel();
        pane2.setPreferredSize(new Dimension(200, 100));
        button = new JButton("My Button");
        button.setPreferredSize(new Dimension(100,50));
        frame.setLayout(new FlowLayout());
    public static void main(String args[]){
        FlowLayoutTest test = new FlowLayoutTest();

When we run the program, the output will be:

The Flow Layout adds its component based on the order of how they are added.

First, we have added pane1, so it will be in the top left of our frame. Next, we have added our button. Since there is still enough room or width that was left when we added our first panel, our button will be placed on the top, next on the panel. Lastly, we have added our pane2. Our pane2 has a width of 200 and our frame has only 500 in width and we have already consume 400 of its width when we place our pane1(300 in width) and our button(100 in width), and what is left is only 100 in width which is not enough for our pane2. Therefore pane2 will be added on the next row, below our pane1.

Next tutorial will be about the Border Layout which is another layout manager.

Share this tutorial!