The basic idea is that Constraints are applied to a Container to determine how the Component is placed on the Container.
What Are Constraints?
Constraints control how the component is placed on a container. There are 11 constraints altogether, though I commonly use only 6.
The Constraints
- gridx: specifies the x coordinate for the upper-left corner
- gridy: specifies the y coordinate for the upper-left corner
- gridwidth: specifies the number of columns to span
- gridheight: specifies the number of rows to span
- fill: specifies how the component fills the area: BOTH, NONE, HORIZONTAL, VERTICAL
- anchor: specifies how to position the component in the area: CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST
- weightx: specifies how to distribute extra horizontal space
- weighty: specifies how to distribute extra vertical space
- ipadx: specifies the internal padding to add to the minimum width
- ipady: specifies the internal padding to add to the minimum height
- insets: specifies the external padding between the component and the edges of its display area
Before You Begin
- Get some graph paper.
- Sketch the layout of the components.
- Draw a rectangle to enclose the components.
- Number the rows top to bottom starting at 0.
- Number the columns left to right starting at 0.
- You now have your first 4 constraints.
The Code
- Create the Component
- Create the Constraints
- Apply the Constraints to the Container
- Add the Component to the Container
I’ve written a method called “gbc” that accepts the first 6 constraints listed above as arguments and returns a GridBagConstraints object.
I usually create my own constants for the GridBagConstraints constants, just for keeping the code smaller.
cmdCalc = new Button("Calculate"); gbcLocal = gbc(0, 0, 1, 1, intFillN, intAnchorC); gblLocal.setConstraints(cmdCalc, gbcLocal); pnlMain.add(cmdCalc);
Finished!
The Layout Manager manages the grid for you at display time
The code: GridBagDemo.java
The Applet: