Java Swing FlowLayout Example

The FlowLayout manager is the simplest layout manager in the Java Swing toolkit. It is the default layout manager for the JPanel component.
The implicit layout manager of the JPanel component is FlowLayout. We do not have to set it manually.
There are three constructors available for the FlowLayout manager. The first one creates a manager with implicit values. Centered with 5px horizontal and vertical spaces. The others allow specifying those parameters.
FlowLayout()
FlowLayout(int align)
FlowLayout(int align, int hgap, int vgap) 

Java Swing FlowLayout Example

The following example demonstrates the usage of the FlowLayout manager. The example shows a button, a tree component, and a text area component in the window.
package net.javaguides.javaswing.examples;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTree;
import java.awt.Dimension;
import java.awt.EventQueue;

/**
 * Class demonstrates the usage of FlowLayout manager.
 * @author javaguides.net
 *
 */
public class FlowLayoutExample extends JFrame {

    private static final long serialVersionUID = 1 L;

    public FlowLayoutExample() {

        initUI();
    }

    private void initUI() {

        JPanel panel = new JPanel();

        JButton button = new JButton("button");
        panel.add(button);

        JTree tree = new JTree();
        panel.add(tree);

        JTextArea area = new JTextArea("Text Area");
        area.setPreferredSize(new Dimension(200, 200));

        panel.add(area);

        add(panel);

        pack();

        setTitle("FlowLayout example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() - > {
            FlowLayoutExample ex = new FlowLayoutExample();
            ex.setVisible(true);
        });
    }
}

Output


Comments