Java Layout Managers
Java Layout Managers
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
The Border Layout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the
default layout of frame or window. The Border Layout provides five constants for
each region:
1. public static final int NORTH
o JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Java Grid Layout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
o public void next(Container parent): is used to flip to the next card of the
given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
The Java GridBag Layout class is used to align components vertically, horizontally
or along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages each component's minimum
and preferred sizes in order to determine component's size.
package gridbaglayoutdemo;
import java.awt.*;
import javax.swing.*;
cst.gridx = 2;
cst.gridy = 0;
panel.add(btn3, cst);
// add button 4 to the panel
cst.fill = GridBagConstraints.HORIZONTAL;
cst.gridwidth = 3;
cst.gridx = 0;
cst.gridy = 1;
panel.add(btn4,cst);
panel.add(btn5,cst);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.getContentPane().add(panel);
frame.setVisible(true);
}