javacodex.com
Java Examples
Java Examples
memu home questions

GridBagLayout

The GridBagLayout lays out components in a grid of rectangular cells arranged in rows and columns similar to the GridLayout. However, it is much more powerful than the GridLayout. Its power comes with an added complexity in its usage. It is not as easy to use as the GridLayout. There are so many things you can customize in the GridBagLayout that it becomes hard to learn and use all of its features quickly.

Source: (GridBagLayoutExample.java)

import java.awt.*;
import javax.swing.*;
 
public class GridBagLayoutExample {
 
  public static void main(String[] arguments) {
 
    // main window
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridBagLayoutExample Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // set main window to use GridBagLayout
    frame.setLayout(new GridBagLayout());
 
    // Define the common constraints
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
 
    // add a bunch of stuff to the frame
    JButton b1 = new JButton("Button1"); // Row 0, Col 0, Width 1
    c.gridx = 0; 
    c.gridy = 0; 
    c.gridwidth = 1;
    frame.add(b1,c);
 
    JButton b2 = new JButton("Button2"); // Row 0, Col 1, Width 1
    c.gridx = 0; 
    c.gridx = 1; 
    c.gridwidth = 1;
    frame.add(b2,c);
 
    JButton b3 = new JButton("Button3"); // Row 0, Col 2, Width 1
    c.gridy = 0; 
    c.gridx = 2;
    c.gridwidth = 1;
    frame.add(b3,c);
 
    JButton b4 = new JButton("Button4"); // Row 1, Col 0, Width 2
    c.gridy = 1; 
    c.gridx = 0;
    c.gridwidth = 2;
    frame.add(b4,c);
 
    JButton b5 = new JButton("Button5"); // Row 1, Col 3, Width 1
    c.gridy = 1; 
    c.gridx = 2;
    c.gridwidth = 1;
    frame.add(b5,c);
 
    JButton b6 = new JButton("Button6"); // Row 2, Col 0, Width 1
    c.gridy = 2; 
    c.gridx = 0;
    c.gridwidth = 1;
    frame.add(b6,c);
 
    JButton b7 = new JButton("Button7"); // Row 2, Col 1, Width 2
    c.gridy = 2; 
    c.gridx = 1;
    c.gridwidth = 2;
    frame.add(b7,c);
 
    frame.pack();
    frame.setVisible(true);
  }
}
 

Output:

$ java GridBagLayoutExample
Output



Contact: javacodex@yahoo.com