Working With the Layout Manager

Introduction

 
In this article, we are going to describe the Java layout manager and its use for setting the components within a container. A layout manager is an object that implements the LayoutManager interface and determines the size and position of the components within a container. There are several AWT and Swing classes providing layout managers for general use. 
 

Followings are general use Layouts

 
1- BorderLayout
2- BoxLayout
3- FlowLayout
4-CardLayout
5- GridBagLayout
6- GridLayout
 

Border Layout

 
In this type of layout components are placed in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Toolbars that are created using JToolBar must be created within a BorderLayout container if you want to be able to drag and drop the bars away from their starting positions. And every content pane initialized is used by a BorderLayout because the content pane is the main container in all frames. For better understanding see the output of the following example carefully.
 
Example 
  1. import java.awt.BorderLayout;  
  2. import java.awt.Container;  
  3. import java.awt.Dimension;  
  4. import javax.swing.JButton;  
  5. import javax.swing.JFrame;  
  6. import javax.swing.JLabel;  
  7. public class BorderLayoutDemo {  
  8.  public static boolean RIGHT_TO_LEFT = false;  
  9.  public static void addComponentsToPane(Container contentPane) {  
  10.   contentPane.setLayout(new BorderLayout(55));  
  11.   if (!(contentPane.getLayout() instanceof BorderLayout))   
  12.   {  
  13.     contentPane.add(new JLabel("Container doesn't use BorderLayout!"));  
  14.     return;  
  15.   }  
  16.   if (RIGHT_TO_LEFT)  
  17.   {  
  18.    contentPane.setComponentOrientation(  
  19.     java.awt.ComponentOrientation.RIGHT_TO_LEFT);  
  20.   }  
  21.   JButton jbnSampleButtons = new JButton("Top");  
  22.   contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START);  
  23.   jbnSampleButtons = new JButton("CENTER");  
  24.   jbnSampleButtons.setPreferredSize(new Dimension(200100));  
  25.   contentPane.add(jbnSampleButtons, BorderLayout.CENTER);  
  26.   jbnSampleButtons = new JButton("Left");  
  27.   contentPane.add(jbnSampleButtons, BorderLayout.LINE_START);  
  28.   jbnSampleButtons = new JButton("Bottom");  
  29.   contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END);  
  30.   jbnSampleButtons = new JButton("Right");  
  31.   contentPane.add(jbnSampleButtons, BorderLayout.LINE_END);  
  32.  }  
  33.  private static void createAndShowGUI()  
  34.  {  
  35.   JFrame.setDefaultLookAndFeelDecorated(true);  
  36.   JFrame frame = new JFrame("BorderLayout  Demo by abhishek");  
  37.   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  38.   addComponentsToPane(frame.getContentPane());  
  39.   frame.pack();  
  40.   frame.setVisible(true);  
  41.  }  
  42.  public static void main(String[] args) {  
  43.   javax.swing.SwingUtilities.invokeLater(new Runnable()  
  44.    {  
  45.     public void run()  
  46.     {  
  47.      createAndShowGUI();  
  48.     }  
  49.    });  
  50.  }  
Output
 
border.jpg
 

BoxLayout

 
The BoxLayout sets the components in a single row or column. It respects the component's requested maximum sizes and also lets you align components.
 
Example
  1. import java.awt.Dimension;  
  2. import javax.swing.Box;  
  3. import javax.swing.BoxLayout;  
  4. import javax.swing.JButton;  
  5. import javax.swing.JFrame;  
  6. import javax.swing.JPanel;  
  7. import javax.swing.SwingUtilities;  
  8. public class BoxLayoutDemo extends JFrame {  
  9.  public BoxLayoutDemo() {  
  10.   initUI();  
  11.  }  
  12.  public final void initUI() {  
  13.   JPanel basic = new JPanel();  
  14.   basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));  
  15.   add(basic);  
  16.   basic.add(Box.createVerticalGlue());  
  17.   JPanel bottom = new JPanel();  
  18.   bottom.setAlignmentX(1 f);  
  19.   bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));  
  20.   JButton ok = new JButton("OK");  
  21.   JButton close = new JButton("Close");  
  22.   bottom.add(ok);  
  23.   bottom.add(Box.createRigidArea(new Dimension(50)));  
  24.   bottom.add(close);  
  25.   bottom.add(Box.createRigidArea(new Dimension(150)));  
  26.   basic.add(bottom);  
  27.   basic.add(Box.createRigidArea(new Dimension(015)));  
  28.   setTitle("Demo of BoxLayout manager");  
  29.   setSize(300150);  
  30.   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  31.   setLocationRelativeTo(null);  
  32.  }  
  33.  public static void main(String[] args) {  
  34.   SwingUtilities.invokeLater(new Runnable() {  
  35.    public void run() {  
  36.     BoxLayoutDemo ex = new BoxLayoutDemo();  
  37.     ex.setVisible(true);  
  38.    }  
  39.   });  
  40.  }  
  41. }  
Output
 
boxlayout.jpg
 

FlowLayout

 
It is default the layoutmanager of JPanel. And in this layout components are added in a flow (which means a single row) and if the container size is not sufficient then it adds the component to the next new rows.
 
Example
  1. import java.awt.ComponentOrientation;  
  2. import java.awt.Container;  
  3. import java.awt.Dimension;  
  4. import java.awt.FlowLayout;  
  5. import javax.swing.JButton;  
  6. import javax.swing.JCheckBox;  
  7. import javax.swing.JFrame;  
  8. import javax.swing.JLabel;  
  9. import javax.swing.JTextField;  
  10. public class FlowLayoutDemo {  
  11.  public static boolean RIGHT_TO_LEFT = false;  
  12.  public static void addComponents(Container contentPane) {  
  13.   if (RIGHT_TO_LEFT) {  
  14.    contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);  
  15.   }  
  16.   contentPane.setLayout(new FlowLayout());  
  17.   contentPane.add(new JLabel("Label add no 1"));  
  18.   contentPane.add(new JButton("Button add no 2"));  
  19.   contentPane.add(new JCheckBox("JCheckBox add no 3"));  
  20.   contentPane.add(new JTextField("Example made by abhishek"));  
  21.   contentPane.add(new JButton("Button add no 5"));  
  22.  }  
  23.  private static void createAndShowGUI() {  
  24.   JFrame.setDefaultLookAndFeelDecorated(true);  
  25.   JFrame frame = new JFrame("FlowLayout Source Demo") {  
  26.    public Dimension getMinimumSize() {  
  27.     Dimension prefSize = getPreferredSize();  
  28.     return new Dimension(100, prefSize.height);  
  29.    }  
  30.   };  
  31.   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  32.   addComponents(frame.getContentPane());  
  33.   frame.pack();  
  34.   frame.setVisible(true);  
  35.  }  
  36.  public static void main(String[] args) {  
  37.   javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  38.    public void run() {  
  39.     createAndShowGUI();  
  40.    }  
  41.   });  
  42.  }  
  43. }  
Output
 
flow.jpg
 

CardLayout 

 
The CardLayout is often controlled by a Combobox, which means its look and feel depends on the selection of a ComboBox item. You can use a tabbed pane as an alternative of card layout. The CardLayout class lets you implement an area that contains different components at different times.
 
Example 
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3. import java.awt.event.*;  
  4. public class CardLayoutDemo extends JFrame {  
  5.  private int currentCard = 1;  
  6.  private JPanel cardPanel;  
  7.  private CardLayout cl;  
  8.  public CardLayoutDemo() {  
  9.   setTitle("Card Layout Example");  
  10.   setSize(300150);  
  11.   cardPanel = new JPanel();  
  12.   cl = new CardLayout();  
  13.   cardPanel.setLayout(cl);  
  14.   JPanel p1 = new JPanel();  
  15.   JPanel p2 = new JPanel();  
  16.   JPanel p3 = new JPanel();  
  17.   JPanel p4 = new JPanel();  
  18.   JLabel lab1 = new JLabel("CardLayout1");  
  19.   JLabel lab2 = new JLabel("CardLayout2");  
  20.   JLabel lab3 = new JLabel("CardLayout3");  
  21.   JLabel lab4 = new JLabel("CardLayout4");  
  22.   p1.add(lab1);  
  23.   p2.add(lab2);  
  24.   p3.add(lab3);  
  25.   p4.add(lab4);  
  26.   cardPanel.add(p1, "1");  
  27.   cardPanel.add(p2, "2");  
  28.   cardPanel.add(p3, "3");  
  29.   cardPanel.add(p4, "4");  
  30.   JPanel buttonPanel = new JPanel();  
  31.   JButton b1 = new JButton("Previous");  
  32.   JButton b2 = new JButton("Next");  
  33.   buttonPanel.add(b1);  
  34.   buttonPanel.add(b2);  
  35.   b1.addActionListener(new ActionListener() {  
  36.    public void actionPerformed(ActionEvent arg0) {  
  37.     if (currentCard > 1)  
  38.     {  
  39.      currentCard -= 1;  
  40.      cl.show(cardPanel, "" + (currentCard));  
  41.     }  
  42.    }  
  43.   });  
  44.   b2.addActionListener(new ActionListener()  
  45.    {  
  46.     public void actionPerformed(ActionEvent arg0)  
  47.     {  
  48.      if (currentCard < 4)  
  49.      {  
  50.       currentCard += 1;  
  51.       cl.show(cardPanel, "" + (currentCard));  
  52.      }  
  53.     }  
  54.    });  
  55.   getContentPane().add(cardPanel, BorderLayout.NORTH);  
  56.   getContentPane().add(buttonPanel, BorderLayout.SOUTH);  
  57.  }  
  58.  public static void main(String[] args)  
  59.  {  
  60.   CardLayoutDemo cl = new CardLayoutDemo();  
  61.   cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  62.   cl.setVisible(true);  
  63.  }  
Output
 
cardlayout1.jpg
 
After clicking on the Next button
 
cardlayout2.jpg  
 

GridBagLayout

 
GridBagLayout is a flexible and sophisticated layout manager. It sets the components into a grid of cells and it allows components to span more then one cell. And the row within grids can have different heights.
Example
  1. import java.awt.*;  
  2. import javax.swing.JButton;  
  3. import javax.swing.JComboBox;  
  4. import javax.swing.JFrame;  
  5. import javax.swing.JTextField;  
  6. public class GridBagLayoutDemo {  
  7.  public static void addComponentsToPane(Container pane) {  
  8.   JButton jbnButton;  
  9.   pane.setLayout(new GridBagLayout());  
  10.   GridBagConstraints gBC = new GridBagConstraints();  
  11.   gBC.fill = GridBagConstraints.HORIZONTAL;  
  12.   jbnButton = new JButton("Button 1");  
  13.   gBC.weightx = 0.5;  
  14.   gBC.gridx = 0;  
  15.   gBC.gridy = 0;  
  16.   pane.add(jbnButton, gBC);  
  17.   JTextField jtf = new JTextField("TextField 1");  
  18.   gBC.gridx = 2;  
  19.   gBC.gridy = 0;  
  20.   jtf.setEditable(false);  
  21.   pane.add(jtf, gBC);  
  22.   jbnButton = new JButton("Button 3");  
  23.   gBC.gridx = 2;  
  24.   gBC.gridy = 0;  
  25.   pane.add(jbnButton, gBC);  
  26.   jbnButton = new JButton("Button 4");  
  27.   gBC.ipady = 40//This component has more breadth compared to  
  28.   other buttons  
  29.   gBC.weightx = 0.0;  
  30.   gBC.gridwidth = 3;  
  31.   gBC.gridx = 0;  
  32.   gBC.gridy = 1;  
  33.   pane.add(jbnButton, gBC);  
  34.   JComboBox jcmbSample = new JComboBox(new String[] {  
  35.    "ComboBox 1",  
  36.    "hi",  
  37.    "hello"  
  38.   });  
  39.   gBC.ipady = 0;  
  40.   gBC.weighty = 1.0;  
  41.   gBC.anchor = GridBagConstraints.PAGE_END;  
  42.   gBC.insets = new Insets(10000); //Padding  
  43.   gBC.gridx = 1;  
  44.   gBC.gridwidth = 2;  
  45.   gBC.gridy = 2;  
  46.   pane.add(jcmbSample, gBC);  
  47.  }  
  48.  private static void createAndShowGUI() {  
  49.   JFrame.setDefaultLookAndFeelDecorated(true);  
  50.   JFrame frame = new JFrame("GridBagLayout Source Demo");  
  51.   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  52.   addComponentsToPane(frame.getContentPane());  
  53.   frame.pack();  
  54.   frame.setVisible(true);  
  55.  }  
  56.  public static void main(String[] args) {  
  57.   javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  58.    public void run() {  
  59.     createAndShowGUI();  
  60.    }  
  61.   });  
  62.  }  
  63. }  
Output
 
When the window size is small:
 
Gridbackmin.jpg
 
When the window size is large:
 
gridbackmax.jpg
 

GridLayout

 
In a GridLayout each component takes all the available space within its cell and each cell size is exactly the same size. In the grid layout if you change your frame or window size then its cell size changes. The cell takes the maximum value possible.
  
Example
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3. public class GridLayoutDemo {  
  4.  public final static boolean RIGHT_TO_LEFT = false;  
  5.  public static void addComponentsToPane(Container contentPane) {  
  6.   if (RIGHT_TO_LEFT) {  
  7.    contentPane.setComponentOrientation(  
  8.     ComponentOrientation.RIGHT_TO_LEFT);  
  9.   }  
  10.   contentPane.setLayout(new GridLayout(02));  
  11.   contentPane.add(new JLabel("My label "));  
  12.   contentPane.add(new JButton("My button"));  
  13.   contentPane.add(new JCheckBox(" MY CheckBox"));  
  14.   contentPane.add(new JTextField("this developed by abhishek"));  
  15.   contentPane.add(new JButton("my button 1"));  
  16.  }  
  17.  private static void createAndShowGUI() {  
  18.   JFrame.setDefaultLookAndFeelDecorated(true);  
  19.   JFrame frame = new JFrame("GridLayout Source Demo");  
  20.   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  21.   addComponentsToPane(frame.getContentPane());  
  22.   frame.pack();  
  23.   frame.setVisible(true);  
  24.  }  
  25.  public static void main(String[] args) {  
  26.   javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  27.    public void run() {  
  28.     createAndShowGUI();  
  29.    }  
  30.   });  
  31.  }  
  32. }  
Output
 
grid.jpg
 
Resources
 


Similar Articles