Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.4. Layouts  >   5.4.1. How to use FlowLayout

5.4.1. How to use FlowLayout
Last updated: 1 February 2013.

FlowLayout is the default layout manager for the class JPanel. As its name implies, it just places components in a row from left to right. The size of each added component is its preferred size. If no space is available for a newly added component, a new row is added. In the next sample, I am creating a JFrame containing a JPanel that is used as a base content pane to which buttons are added:

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public final class FlowLayoutExample extends JFrame {

   
public FlowLayoutExample(){
         
init();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
private void addComponents(){
         
JPanel panel = new JPanel(new FlowLayout());
          // this statement is the same as : JPanel panel = new JPanel();

         
panel.add(new JButton("First Button"));
          panel.add
(new JButton("Button 2"));
          panel.add
(new JButton("3"));
          panel.add
(new JButton("Very last Button"));

         
this.add(panel);
   
}


   
private void init(){
         
setTitle("FlowLayoutExample");
          setSize
(500, 70);
          setLocation
(200, 100);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new FlowLayoutExample();
               
}
          })
;
   
}
}




Here is what it looks like on a Mac OS X system:


Flow layout example


The class FlowLayout provides methods to set the horizontal and vertical gap between components: setHgap(int hgap) and setVgap(int vgap). You can also set the alignment of the layout by calling the method setAlignment(int align). The possible values for align are FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER, FlowLayout.LEADING and FlowLayout.TRAILING.


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.4. Layouts  >   5.4.1. How to use FlowLayout
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.4. Layouts  >   5.4.2. How to use BoxLayout

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7