GridBagLayout

Textbook examples

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GridBagDemo extends JFrame { 
   private Container container;
   private GridBagLayout gbLayout;
   private GridBagConstraints gbConstraints; 
    
   public GridBagDemo()
   {
      super( "GridBagLayout" );

      container = getContentPane();
      gbLayout = new GridBagLayout();
      container.setLayout( gbLayout );   

      // instantiate gridbag constraints
      gbConstraints = new GridBagConstraints();

      JTextArea ta = new JTextArea( "TextArea1", 5, 10 );
      JTextArea tx = new JTextArea( "TextArea2", 2, 2 );
      String names[] = { "Iron", "Steel", "Brass" };
      JComboBox cb = new JComboBox( names );
      JTextField tf = new JTextField( "TextField" );
      JButton b1 = new JButton( "Button 1" );
      JButton b2 = new JButton( "Button 2" );
      JButton b3 = new JButton( "Button 3" );

      // text area
      // weightx and weighty are both 0: the default
      // anchor for all components is CENTER: the default
      gbConstraints.fill = GridBagConstraints.BOTH;
      addComponent( ta, 0, 0, 1, 3 );    
       
      // button b1
      // weightx and weighty are both 0: the default
      gbConstraints.fill = GridBagConstraints.HORIZONTAL;
      addComponent( b1, 0, 1, 2, 1 );
      
      // combo box
      // weightx and weighty are both 0: the default
      // fill is HORIZONTAL
      addComponent( cb, 2, 1, 2, 1 );             

      // button b2
      gbConstraints.weightx = 1000;  // can grow wider
      gbConstraints.weighty = 1;     // can grow taller
      gbConstraints.fill = GridBagConstraints.BOTH;
      addComponent( b2, 1, 1, 1, 1 );
       
      // button b3
      // fill is BOTH
      gbConstraints.weightx = 0;
      gbConstraints.weighty = 0;    
      addComponent( b3, 1, 2, 1, 1 );
       
      // textfield
      // weightx and weighty are both 0: fill is BOTH
      addComponent( tf, 3, 0, 2, 1 );

      // textarea
      // weightx and weighty are both 0: fill is BOTH
      addComponent( tx, 3, 2, 1, 1 );

      setSize( 300, 150 );
      show();
   }

   // addComponent is programmer defined
   private void addComponent( Component c,
      int row, int column, int width, int height )
   {
      // set gridx and gridy 
      gbConstraints.gridx = column;
      gbConstraints.gridy = row;

      // set gridwidth and gridheight
      gbConstraints.gridwidth = width;   
      gbConstraints.gridheight = height;

      // set constraints
      gbLayout.setConstraints( c, gbConstraints );  
      container.add( c );      // add component 
   }

   public static void main( String args[] )
   {
      GridBagDemo app = new GridBagDemo();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

GridBagDemo2.java

A variation of GridBagLayout does not use the gridx and gridy. Rather GridBagConstraints constants RELATIVE and REMAINDER are used in their place. RELATIVE specifies that the next-to-last component in a particular row should be placed to the right of the previous component in that row. REMAINDER specifies that a component is the last component in a row. Any component that is not the second-to-last or last component on a row must specify values for GridBagConstraints variables gridwidth and gridheight.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GridBagDemo2 extends JFrame { 
   private GridBagLayout gbLayout;
   private GridBagConstraints gbConstraints;
   private Container container;
    
   public GridBagDemo2()
   {
      super( "GridBagLayout" );

      container = getContentPane();
      gbLayout = new GridBagLayout();
      container.setLayout( gbLayout );   

      // instantiate gridbag constraints
      gbConstraints = new GridBagConstraints();

      // create GUI components
      String metals[] = { "Copper", "Aluminum", "Silver" };
      JComboBox comboBox = new JComboBox( metals );

      JTextField textField = new JTextField( "TextField" );

      String fonts[] = { "Serif", "Monospaced" };
      JList list = new JList( fonts );

      String names[] =
         { "zero", "one", "two", "three", "four" };
      JButton buttons[] = new JButton[ names.length ];

      for ( int i = 0; i < buttons.length; i++ )
         buttons[ i ] = new JButton( names[ i ] );

      // define GUI component constraints
      // textField
      gbConstraints.weightx = 1;
      gbConstraints.weighty = 1;  
      gbConstraints.fill = GridBagConstraints.BOTH;
      gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
      addComponent( textField );

      // buttons[0] -- weightx and weighty are 1: fill is BOTH
      gbConstraints.gridwidth = 1;
      addComponent( buttons[ 0 ] );

      // buttons[1] -- weightx and weighty are 1: fill is BOTH
      gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
      addComponent( buttons[ 1 ] );

      // buttons[2] -- weightx and weighty are 1: fill is BOTH
      gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
      addComponent( buttons[ 2 ] );

      // comboBox -- weightx is 1: fill is BOTH
      gbConstraints.weighty = 0;
      gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
      addComponent( comboBox );
      
      // buttons[3] -- weightx is 1: fill is BOTH
      gbConstraints.weighty = 1;
      gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
      addComponent( buttons[ 3 ] ); 

      // buttons[4] -- weightx and weighty are 1: fill is BOTH
      gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
      addComponent( buttons[ 4 ] );

      // list -- weightx and weighty are 1: fill is BOTH
      gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
      addComponent( list );

      setSize( 300, 200 );
      show();
   }

   // addComponent is programmer-defined
   private void addComponent( Component c ) 
   {
      gbLayout.setConstraints( c, gbConstraints );
      container.add( c );      // add component
   }   

   public static void main( String args[] )
   {
      GridBagDemo2 app = new GridBagDemo2();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

Tutorial Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridBagWindow extends JFrame {
    boolean inAnApplet = true;
    final boolean shouldFill = true;
    final boolean shouldWeightX = true;
     
    public GridBagWindow() {
        JButton button;
        Container contentPane = getContentPane();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        contentPane.setLayout(gridbag);
        if (shouldFill) {
            //natural height, maximum width
            c.fill = GridBagConstraints.HORIZONTAL; 
        }
   
        button = new JButton("Button 1");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.gridx = 0;
        c.gridy = 0;
        gridbag.setConstraints(button, c);
        contentPane.add(button);

        button = new JButton("2");
        c.gridx = 1;
        c.gridy = 0;
        gridbag.setConstraints(button, c);
        contentPane.add(button);

        button = new JButton("Button 3");
        c.gridx = 2;
        c.gridy = 0;
        gridbag.setConstraints(button, c);
        contentPane.add(button);

        button = new JButton("Long-Named Button 4");
        c.ipady = 40;      //make this component tall
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 1;
        gridbag.setConstraints(button, c);
        contentPane.add(button);

        button = new JButton("Button 5");
        c.ipady = 0;       //reset to default
        c.weighty = 1.0;   //request any extra vertical space
        c.anchor = GridBagConstraints.SOUTH; //bottom of space
        c.insets = new Insets(10,0,0,0);  //top padding
        c.gridx = 1;       //aligned with button 2
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 2;       //third row
        gridbag.setConstraints(button, c);
        contentPane.add(button);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (inAnApplet) {
                    dispose();
                } else {
                    System.exit(0);
                }
            }
        });
    }

    public static void main(String args[]) {
        GridBagWindow window = new GridBagWindow();
        window.inAnApplet = false;

        window.setTitle("GridBagLayout");
        window.pack();
        window.setVisible(true);
    }
}


Maintained by John Loomis, last updated 6 July 2000