Gridwidth and gridheight Constraints for GridBagLayout - Java Swing

Java examples for Swing:GridBagLayout

Introduction

gridwidth and gridheight set the width and height of the display area of a component, respectively.

The default value for both is 1, which means that a component is placed in one cell.

gridwidth = 2 for a component will have two cells wide.

gridheight = 2 for a component will have two cells high.

gridwidth is like HTML Table colspan and gridheight is like HTML table rowspan.

gridwidth REMAINDER means that the component will span from its gridx cell to the remainder of the row.

gridheight RELATIVE means that the height of the component will be from its gridy to the second last cell.

Demo Code

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("GridBagLayout");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();

    JButton b3 = new JButton("Button 3");

    // Expand the component to fill the whole cell
    gbc.fill = GridBagConstraints.BOTH;

    gbc.gridx = 0;//w w w . j a va2s.  c o  m
    gbc.gridy = 0;
    frame.add(new JButton("Button 1"), gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = GridBagConstraints.RELATIVE;
    frame.add(new JButton("Button 2"), gbc);

    gbc.gridx = GridBagConstraints.RELATIVE;
    gbc.gridy = 0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    frame.add(new JButton("Button 3"), gbc);

    // Reset grid width to its default value 1
    gbc.gridwidth = 1;

    // Place six JButtons in second row
    gbc.gridy = 1;
    for (int i = 0; i < 6; i++) {
      gbc.gridx = i;
      frame.add(new JButton("Button " + (i + 4)), gbc);
    }

    frame.add(b3, gbc);
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials