Controls and layout managers
Layout managers
GridBagLayout manager
The GridBagLayout manager is the most flexible and the most complex. It is similar to the GridLayout manager in the sense that both layout managers arrange components in a grid. The components can vary in size, however, and can be added in any order in GridBagLayout.
A user interface that uses the GridBagLayout manager
How to work with the GridBagLayout manager
- Diagram or sketch the user interface and divide it into rows and columns.
- Set the layout to an object of the GridBagLayout class:
- Create a GridBagConstraints object to hold positioning data:
- Set the constraints in the GridBagConstraints object:
- Use the add method of the Container class that specifies the component and its constraints:
- Repeat steps 4 and 5 until all components have been added.
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 1; c.insets = new Insets(5, 5, 5, 5);
add(Component, GridBagConstraints)
The pack method of the Window class
Method | Description |
---|---|
pack() | Resizes the window to accommodate the components it contains. |
Note
- When you use the GridBagLayout manager, it's helpful to use the pack method of the Window class to set the frame size. That way, the size of the frame will automatically be set to accommodate the components that are added to it.