Skip to content


About The GridBagConstraints Example

AWT GridBagConstraints gridx, gridy on GridBagLayout

Here, the GridBagLayout comprises of 16 cells. In x axis, we have 4 slots and in y axis we have 4 slots. These together form a grid of 16 cells. The gridx and gridy properties of GridBagConstraints represents these slots. In the above picture you can also see placement of the 9 buttons and how they vary in size.

The properties gridheight & gridwidth tell how many cells a control must cover. The gridwidth property spawns a control horizontally and gridheight property spawns it vertically. In this example, we will create 9 buttons and add it to the AWT Frame window, which is managed by GridBagLayout. Along the way, we will learn about the gridx, gridy, gridwidth and gridheight properties of the GridBagConstraints.

GridBagLayout WeightX WeightY Fill Combination

AWT GridBagLayout GridBagConstraints Weightx, WeightY & Fill

We had seen many Layouts in past examples on Java AWT. The GridBagLayout is the most flexible layout in the Java AWT packages. But this comes with the cost of complexity held in the setup of GridBagLayout. You can imagine GridBagLayout as GridLayout with change in cell sizes. Here, we can add controls in relation with the existing one.

The GridBagLayout makes use of the specific settings for each controls which can be set using the GridBagConstraints class. Before adding the controls to the GridBagLayout class, we need to set these component specific setup rules. The bag layout will make use of these setup factors to arrange the components in the parent container.