Java Swing GridBagLayout

GridBagLayout extends the capabilities of the GridLayout. Like GridLayout, GridBagLayout places component in each individual cell in a grid. In addition, GridBagLayout also allows the component to span to multiple columns or rows. In order to do so, GridBagConstraints is used for each component.

In order to use GridBagLayout, first, you need to create a GridBagConstraints object and fill appropriate properties. Then you can add a component to a container using this GridBagConstraints object.

The following is the typical code snippet to use GridBagConstraints along with GridBagLayout:

Here are properties of GridBagConstraints and their descriptions:

PropertiesDescription
 gridx,gridySpecify the row and column from top to bottom and from left to right starting from zero. For example gridx = 0, gridy = 0 is the top left cell of the grid.
gridwidth, gridheightSpecify number of rows (gridheight) and columns (gridwidth) to which a component can span. The default value of gridwidth and gridheight is 1.
 fillThis property is used to resolve whether and how to resize the component when the component’s display region is larger than the component’s requested size. The values for fill property are: NONE, VERTICAL, HORIZONTAL, VERTICAL and BOTH.
 ipadx, ipadyThe ipadx, ipady property are used to set the internal padding of the component.
insetsThe insets property is used to set the external padding of the component.
weightx, weightyThese properties are used to specify how to distribute space between rows(weighty) and columns(weightx).
anchorThe anchor property is used to determine where to place the component when the component is smaller than display area in the container.

GridBagLayout Demo Application

Let’s take a look at an example to see how GridBagLayout works.

Here is the screenshot of the GridBagLayout demo application:

Java GridBagLayout

  • Was this tutorial helpful ?
  • YesNo