Java AWT | GridBagLayout Class
GridBagLayout class is a flexible layout manager. It is used to aligns the components horizontally, vertically, or along their baseline. It doesn’t require the components of the same size. Each GridBagLayout object manages a rectangular grid of cells, dynamic with each component occupying one or more cells, called its display area. GridBagLayout components are associated with the instance of GridBagConstraints. These constraints are used to define the component’s display area and their positions. In addition to its constraints object, the GridBagLayout also considers each component’s minimum and preferred sizes in order to determine a component’s size. GridBagLayout components are also arranged in the rectangular grid but can have different sizes and can occupy the multiple rows or columns.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- GridBagLayout(): It is used to creates a grid bag layout manager.
Commonly Used Methods:
- removeLayoutComponent(Component cmp): Removes the specified component from this layout.
- getLayoutAlignmentY(Container p): Returns the alignment along the y-axis.
- addLayoutComponent(Component cmp, Object cons): Add the specified component with the specified name to the layout.
- toString(): Returns a string representation of this grid bag layout’s values.
- getLayoutAlignmentX(Container p): Returns the alignment along the x-axis.
- getConstraints(Component cmp): Gets the constraints for the specified component.
- maximumLayoutSize(Container tar): Returns the maximum dimensions for this layout given the components in the specified target container.
- minimumLayoutSize(Container par): Determines the minimum size of the parent container using this grid bag layout.
Below programs illustrate the GridBagLayout class:
- Program 1: Below program arranges the several row and column components in a JFrame, whose instance class is named as “Gridbagdemo”. We create 4 JButton components named “java“, “layout“, “manager“, “demo” and then add them to the JFrame by the method add(). We set the size and visibility of the frame by method setSize() and setVisible(). The layout is set by the method setLayout().
- Program 2: Below program arranges the several row and column components in a JFrame, whose instance class is named as “Gridbagdemo”. We create 5 JButton components and then add them to the JFrame by the method add(). We set the title, size and visibility of the frame by method setTitle, setSize() and setVisible(). The layout is set by the method setLayout().
Note: The above programs might not run in an online IDE. Please use an offline compiler.