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
- import java.awt.BorderLayout;
- import java.awt.Container;
- import java.awt.Dimension;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class BorderLayoutDemo {
- public static boolean RIGHT_TO_LEFT = false;
- public static void addComponentsToPane(Container contentPane) {
- contentPane.setLayout(new BorderLayout(5, 5));
- if (!(contentPane.getLayout() instanceof BorderLayout))
- {
- contentPane.add(new JLabel("Container doesn't use BorderLayout!"));
- return;
- }
- if (RIGHT_TO_LEFT)
- {
- contentPane.setComponentOrientation(
- java.awt.ComponentOrientation.RIGHT_TO_LEFT);
- }
- JButton jbnSampleButtons = new JButton("Top");
- contentPane.add(jbnSampleButtons, BorderLayout.PAGE_START);
- jbnSampleButtons = new JButton("CENTER");
- jbnSampleButtons.setPreferredSize(new Dimension(200, 100));
- contentPane.add(jbnSampleButtons, BorderLayout.CENTER);
- jbnSampleButtons = new JButton("Left");
- contentPane.add(jbnSampleButtons, BorderLayout.LINE_START);
- jbnSampleButtons = new JButton("Bottom");
- contentPane.add(jbnSampleButtons, BorderLayout.PAGE_END);
- jbnSampleButtons = new JButton("Right");
- contentPane.add(jbnSampleButtons, BorderLayout.LINE_END);
- }
- private static void createAndShowGUI()
- {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JFrame frame = new JFrame("BorderLayout Demo by abhishek");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- addComponentsToPane(frame.getContentPane());
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- javax.swing.SwingUtilities.invokeLater(new Runnable()
- {
- public void run()
- {
- createAndShowGUI();
- }
- });
- }
Output
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
- import java.awt.Dimension;
- import javax.swing.Box;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.SwingUtilities;
- public class BoxLayoutDemo extends JFrame {
- public BoxLayoutDemo() {
- initUI();
- }
- public final void initUI() {
- JPanel basic = new JPanel();
- basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
- add(basic);
- basic.add(Box.createVerticalGlue());
- JPanel bottom = new JPanel();
- bottom.setAlignmentX(1 f);
- bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
- JButton ok = new JButton("OK");
- JButton close = new JButton("Close");
- bottom.add(ok);
- bottom.add(Box.createRigidArea(new Dimension(5, 0)));
- bottom.add(close);
- bottom.add(Box.createRigidArea(new Dimension(15, 0)));
- basic.add(bottom);
- basic.add(Box.createRigidArea(new Dimension(0, 15)));
- setTitle("Demo of BoxLayout manager");
- setSize(300, 150);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLocationRelativeTo(null);
- }
- public static void main(String[] args) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- BoxLayoutDemo ex = new BoxLayoutDemo();
- ex.setVisible(true);
- }
- });
- }
- }
Output
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
- import java.awt.ComponentOrientation;
- import java.awt.Container;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import javax.swing.JButton;
- import javax.swing.JCheckBox;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JTextField;
- public class FlowLayoutDemo {
- public static boolean RIGHT_TO_LEFT = false;
- public static void addComponents(Container contentPane) {
- if (RIGHT_TO_LEFT) {
- contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
- }
- contentPane.setLayout(new FlowLayout());
- contentPane.add(new JLabel("Label add no 1"));
- contentPane.add(new JButton("Button add no 2"));
- contentPane.add(new JCheckBox("JCheckBox add no 3"));
- contentPane.add(new JTextField("Example made by abhishek"));
- contentPane.add(new JButton("Button add no 5"));
- }
- private static void createAndShowGUI() {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JFrame frame = new JFrame("FlowLayout Source Demo") {
- public Dimension getMinimumSize() {
- Dimension prefSize = getPreferredSize();
- return new Dimension(100, prefSize.height);
- }
- };
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- addComponents(frame.getContentPane());
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- }
Output
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
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class CardLayoutDemo extends JFrame {
- private int currentCard = 1;
- private JPanel cardPanel;
- private CardLayout cl;
- public CardLayoutDemo() {
- setTitle("Card Layout Example");
- setSize(300, 150);
- cardPanel = new JPanel();
- cl = new CardLayout();
- cardPanel.setLayout(cl);
- JPanel p1 = new JPanel();
- JPanel p2 = new JPanel();
- JPanel p3 = new JPanel();
- JPanel p4 = new JPanel();
- JLabel lab1 = new JLabel("CardLayout1");
- JLabel lab2 = new JLabel("CardLayout2");
- JLabel lab3 = new JLabel("CardLayout3");
- JLabel lab4 = new JLabel("CardLayout4");
- p1.add(lab1);
- p2.add(lab2);
- p3.add(lab3);
- p4.add(lab4);
- cardPanel.add(p1, "1");
- cardPanel.add(p2, "2");
- cardPanel.add(p3, "3");
- cardPanel.add(p4, "4");
- JPanel buttonPanel = new JPanel();
- JButton b1 = new JButton("Previous");
- JButton b2 = new JButton("Next");
- buttonPanel.add(b1);
- buttonPanel.add(b2);
- b1.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent arg0) {
- if (currentCard > 1)
- {
- currentCard -= 1;
- cl.show(cardPanel, "" + (currentCard));
- }
- }
- });
- b2.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent arg0)
- {
- if (currentCard < 4)
- {
- currentCard += 1;
- cl.show(cardPanel, "" + (currentCard));
- }
- }
- });
- getContentPane().add(cardPanel, BorderLayout.NORTH);
- getContentPane().add(buttonPanel, BorderLayout.SOUTH);
- }
- public static void main(String[] args)
- {
- CardLayoutDemo cl = new CardLayoutDemo();
- cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- cl.setVisible(true);
- }
After clicking on the Next button
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
- import java.awt.*;
- import javax.swing.JButton;
- import javax.swing.JComboBox;
- import javax.swing.JFrame;
- import javax.swing.JTextField;
- public class GridBagLayoutDemo {
- public static void addComponentsToPane(Container pane) {
- JButton jbnButton;
- pane.setLayout(new GridBagLayout());
- GridBagConstraints gBC = new GridBagConstraints();
- gBC.fill = GridBagConstraints.HORIZONTAL;
- jbnButton = new JButton("Button 1");
- gBC.weightx = 0.5;
- gBC.gridx = 0;
- gBC.gridy = 0;
- pane.add(jbnButton, gBC);
- JTextField jtf = new JTextField("TextField 1");
- gBC.gridx = 2;
- gBC.gridy = 0;
- jtf.setEditable(false);
- pane.add(jtf, gBC);
- jbnButton = new JButton("Button 3");
- gBC.gridx = 2;
- gBC.gridy = 0;
- pane.add(jbnButton, gBC);
- jbnButton = new JButton("Button 4");
- gBC.ipady = 40;
- other buttons
- gBC.weightx = 0.0;
- gBC.gridwidth = 3;
- gBC.gridx = 0;
- gBC.gridy = 1;
- pane.add(jbnButton, gBC);
- JComboBox jcmbSample = new JComboBox(new String[] {
- "ComboBox 1",
- "hi",
- "hello"
- });
- gBC.ipady = 0;
- gBC.weighty = 1.0;
- gBC.anchor = GridBagConstraints.PAGE_END;
- gBC.insets = new Insets(10, 0, 0, 0);
- gBC.gridx = 1;
- gBC.gridwidth = 2;
- gBC.gridy = 2;
- pane.add(jcmbSample, gBC);
- }
- private static void createAndShowGUI() {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JFrame frame = new JFrame("GridBagLayout Source Demo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- addComponentsToPane(frame.getContentPane());
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- }
Output
When the window size is small:
When the window size is large:
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
- import java.awt.*;
- import javax.swing.*;
- public class GridLayoutDemo {
- public final static boolean RIGHT_TO_LEFT = false;
- public static void addComponentsToPane(Container contentPane) {
- if (RIGHT_TO_LEFT) {
- contentPane.setComponentOrientation(
- ComponentOrientation.RIGHT_TO_LEFT);
- }
- contentPane.setLayout(new GridLayout(0, 2));
- contentPane.add(new JLabel("My label "));
- contentPane.add(new JButton("My button"));
- contentPane.add(new JCheckBox(" MY CheckBox"));
- contentPane.add(new JTextField("this developed by abhishek"));
- contentPane.add(new JButton("my button 1"));
- }
- private static void createAndShowGUI() {
- JFrame.setDefaultLookAndFeelDecorated(true);
- JFrame frame = new JFrame("GridLayout Source Demo");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- addComponentsToPane(frame.getContentPane());
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- }
Output
Resources