Java Swing FlowLayout

FlowLayout is the simplest layout in Java Swing layouts. The FlowLayout places components from left to right in a row using preferred component sizes until no space is available in the container.

When no space is available, a new row is started. The placement of the component depends on the size of the container. Therefore, you cannot guarantee which row the component is placed.

The FlowLayout is useful as a pad for a single component to make sure that the component will be placed at the center area of a container. Notice that FlowLayout is the default layout of JPanel container.

package flowlayoutdemo; import java.awt.*; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("FlowLayout Demo"); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); JButton btn4 = new JButton("Button 4"); JButton btn5 = new JButton("Button 5"); // FlowLayout is default for JPanel JPanel panel = new JPanel(new FlowLayout()); // add buttons to the panel panel.add(btn1); panel.add(btn2); panel.add(btn3); panel.add(btn4); panel.add(btn5); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,150); frame.getContentPane().add(panel); frame.setVisible(true); } }
Code language: JavaScript (javascript)