- frame.setLayout(new GridBagLayout()); //Set GridBagLayout for frame
- pane.setLayout(new GridBagLayout()); //Set GridBagLayout for Panel
- JPanel pane = new JPanel(new GridBagLayout()); //Set GridBagLayout for Panel
- GridBagConstraints c = new GridBagConstraints() //Initialize a GridBagConstraint
How does GridBagLayout work?
Layouts are used whenever you want your components to not just be displayed next to each other. The
GridBagLayout is a useful one, as it divides your window into rows and columns, and you decide which row and column to put components into, as well as how many rows and colums big the component is.
Let's take this window as an example. Grid lines have been marked on to show the layout.
Here, I have created 6 components, laid out using a GridBagLayout.
Note that position
0, 0 is at the top left:
x (column) values increase from left to right,
y (row) values increase from top to bottom.
To start laying out components in a
GridBagLayout, first set the layout of your
JFrame or content pane.
Note that you never define the size of the grid. This is done automatically as you add your components.
Afterwards, you will need to create a
To make sure that your components fill up the size of the window, you may want to set the weight of all componets to 1. Weight is used to determine how to distribute space among columns and rows.
Another thing that you may want to do is make sure that components take up as much horizontal space as they can.
You can also set other fill options if you wish.
When creating components, you will want to set where on the grid it should go, and how many grid tiles it should use. For example, to place a button in the 3rd row in the 2nd column, and take up a 5 x 5 grid space, do the following. Keep in mind that the grid starts at
0, 0, not
When adding components to your window, remember to pass the constraints as a parameter. This can be seen in the last line in the code example above.
You can reuse the same
GridBagConstraints for every component - changing it after adding a component doesn't change the previously added component.
Here's the code for the example at the start of this section.