Java Reference
In-Depth Information
With the constraints for the buttons as before, the
window will look like:
Both the
Push
and the
Press
button occupy the same space in the container, but, because
fill
is set to
NONE
, they are not expanded to fill the space in either direction. The
ipadx
and
ipady
constraints
specify by how much the buttons are to be expanded from their preferred size - by thirty pixels on the
left and right, and ten pixels on the top and bottom. The overall arrangement remains the same.
You need to experiment with using
GridBagLayout
and
GridBagConstraints
to get a good feel
for how the layout manager works because you are likely to find yourself using it quite often.
Using a SpringLayout Manager
You can set the layout manager for the content pane of a
JFrame
object,
aWindow
, to be a
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
component in the container according to a set of constraints that are defined by
Spring
objects. Every
component within a container using a
SpringLayout
manager has an object associated with it of type
SpringLayout.constraints
that can define constraints on the position of each of the four edges of
the component. Before you can access the
SpringLayout.constraints
object for an object, you
must first add the object to the container. For example:
JButton button = new JButton("Press Me");
content.add(button);
Now we can call the
getConstraint()
method for the
SpringLayout
object to obtain the object
encapsulating the constraints:
SpringLayout.Constraints buttonConstr = layout.getConstraints(button);
To constrain the location and size of the
button
object, we will call methods of the
buttonConstr
object to set individual constraints.