by Dinesh Thakur Category: Swing

The FlowLayout is the simplest manager. The components are arranged from left to right in the order in which they appear, i.e., in the order they are added. When there is no more space on a line, another line is created, resembling a text editor. This process is automatically done according to the container size.

Configuration Management - It is possible to specify the space between components, default is 5 pixels. You can also specify the alignment of the components in a line, for this, one of the following constants are used: FlowLayout.CENTER, FlowLayout.RIGHT or FlowLayout.LEFT . for configured administrator have the following distribution builders:

public FlowLayout()

public FlowLayout(int align)

public FlowLayout(int align, int hgap, int vgap)

Where align is the alignment, hgap is the horizontal space and vgap is the vertical space.

preferred container size - The preferred size of the container is one that makes all the components fit in a single line. The container will as a height size higher and width as the sum of the preferred widths of all component parts, in addition to the gap between them.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaExampleFlowLayout extends JFrame implements ActionListener
  {
      private JButton LBtn = new JButton("Left Button");
      private JButton RBtn = new JButton("Right Button");
      private Container cntnr = getContentPane();
      private FlowLayout layout = new FlowLayout();
      public JavaExampleFlowLayout()
        {
            cntnr.setLayout(layout);
            cntnr.add(LBtn);
            cntnr.add(RBtn);
            LBtn.addActionListener(this);
            RBtn.addActionListener(this);
            setSize(500, 100);
            setVisible(true);
        }
            public void actionPerformed(ActionEvent evnt)
              {
                  Object src = evnt.getSource();
                   if(src == LBtn)
                   layout.setAlignment(FlowLayout.LEFT);
                   else
                   layout.setAlignment(FlowLayout.RIGHT);
                   cntnr.invalidate();
                   cntnr.validate();
             }
                  public static void main(String[] args)
                    {
                       JavaExampleFlowLayout frame = new JavaExampleFlowLayout();
                    }
   }




About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles