• The Layout Manager: GridBag Layout

    This layout one of the complex layout manager but very powerful. A constraint should be define to layout the components properly.

    package com.javapointers.javase;
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    /**
     *
     * @author javapointers
     */
    public class GridBagLayoutTest {
    
        JFrame frame;
        JButton button1, button2;
        JPanel panel;
        GridBagLayout gbl;
        GridBagConstraints gbc;
    
        public GridBagLayoutTest() {
            frame = new JFrame("GridBagLayout Test");
            frame.setSize(500, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            button1 = new JButton("Button 1");
            button2 = new JButton("Button 2");
            panel = new JPanel();
            panel.setBackground(Color.GREEN);
            panel.setPreferredSize(new Dimension(200,300));
    
            gbl = new GridBagLayout();
            gbc = new GridBagConstraints();
    
            frame.setLayout(gbl);
    
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridheight = 1;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.BOTH;
            frame.add(button1, gbc);
    
            gbc.gridx = 1;
            gbc.gridy = 1;
            gbc.gridheight = 2;
            gbc.gridwidth = 2;
            gbc.fill = GridBagConstraints.BOTH;
            frame.add(button2, gbc);
    
            gbc.gridx = 3;
            gbc.gridy = 0;
            gbc.gridheight = 4;
            gbc.gridwidth = 4;
            gbc.fill = GridBagConstraints.BOTH;
            frame.add(panel, gbc);
    
            frame.setVisible(true);
        }
    
        public static void main(String args[]) {
            GridBagLayoutTest test = new GridBagLayoutTest();
        }
    }
    
    

    When we run  our program, the output will be:

    In our above example, we have define GridBagLayout as gbl and GridBagConstraints as gbc. GridBagConstraints define how our components will be layout in our container. Some constraints are:

    • gbc.gridx = 0;

      means that layout the component starting from 0 in x-coordinate.

    • gbc.gridy = 0;

      means that layout the component starting from 0 in y-coordinate.

    • gbc.gridheight = 1;

      means that this component will allocate 1 cell in height.

    • gbc.gridwidth = 1;

      means that this component will allocate 1 cell in width.

    • gbc.fill = GridBagConstraints.BOTH;

      means to fill all the cells horizontally and vertically.

    • frame.add(button1, gbc);

      add the component with the constraints that we defined.

    Related Post