Java Reference
In-Depth Information
You need to experiment with using GridBagLayout and GridBagConstraints to get a good feel for how
the layout manager works because it's only with experience that you can appreciate what you can do with
it.
Using a SpringLayout Manager
You can set the layout manager for the content pane of a JFrame object, aWindow , to be a
javax.swing.SpringLayout manager like this:
SpringLayout layout = new SpringLayout(); // Create a layout manager
Container content = aWindow.getContentPane(); // Get the content pane
content.setLayout(layout);
The layout manager defined by the SpringLayout class determines the position and size of each com-
ponent in the container according to a set of constraints that are defined by javax.swing.Spring objects.
Every component within a container using a SpringLayout manager has an object associated with it of type
SpringLayout.Constraints that defines constraints on the position of each of the four edges of the com-
ponent. Before you can access the SpringLayout.constraints object for a component object, you must
first add the component to the container. For example:
JButton button = new JButton("Press Me");
content.add(button);
Now you can call the getConstraint() method for the SpringLayout object to obtain the object encap-
sulating the constraints:
SpringLayout.Constraints constraints = layout.getConstraints(button);
The argument to the getConstraints() method identifies the component in the container for which you
want to access the constraints object. To constrain the location and size of the button object, you call
methods for the constraints object to set individual constraints.
Understanding Spring Constraints
The top, bottom, left, and right edges of a component are referred to by their compass points: north, south,
west, and east. When you need to refer to a particular edge in your code — for setting a constraint, for
example — you use constants that are defined in the SpringLayout class, NORTH , SOUTH , WEST , and EAST ,
respectively. This is shown in Figure 17-33 .
FIGURE 17-33
 
 
Search WWH ::




Custom Search