CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Layout

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

  1. Diagram or sketch the user interface and divide it into rows and columns.
  2. Set the layout to an object of the GridBagLayout class:
  3. setLayout(new GridBagLayout());
  4. Create a GridBagConstraints object to hold positioning data:
  5. GridBagConstraints c = new GridBagConstraints();
  6. Set the constraints in the GridBagConstraints object:
  7. c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    c.gridheight = 1;
    c.insets = new Insets(5, 5, 5, 5);
    
  8. Use the add method of the Container class that specifies the component and its constraints:
  9. add(Component, GridBagConstraints)
  10. Repeat steps 4 and 5 until all components have been added.

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.
Previous | Summary | GridBagLayout manager | Constraints for a GridBagLayout | Application