Java Reference
In-Depth Information
Container
Origin
Set by
and
setX()
setY()
Position xy
NORTH
XSpring
Component
wSpring
SOUTH
Set by
setWidth()
setHeight()
and
Container
Setting Constraints on a Component
To set the width and height of the component, you call the
setWidth()
and
setHeight()
methods
for its
SpringLayout.Constraints
object:
Spring wSpring = Spring.constant(30,50,70); // Spring we'll use for width
Spring hSpring = Spring.constant(15); // Strut we'll use for height
buttonConstr.setWidth(wSpring); // Set component width constraint
buttonConstr.setHeight(hSpring); // Set component height constraint
The width constraint is applied between the
WEST
and
EAST
edges and the height constraint applies
between the component's
NORTH
and
SOUTH
edges. Since we have specified a strut for the height, there
is no leeway on this constraint; its value is fixed at 15.
If you want to explicitly set an edge constraint for a component, you call the
setConstraint()
method for the component's
SpringLayout.Constraints
object:
layout.getConstraints(newButton)
.setConstraint(StringLayout.EAST, Spring.sum(xSpring, wSpring));
This statement ties the
EAST
edge of the
newButton
component to the
WEST
edge of the container by
a
Spring
object that is the sum of
xSpring
and
wSpring
.
You can also set constraints between pairs of vertical or horizontal edges where one edge can belong to a
different component from the other. For instance, we could add another button to the container like this:
JButton newButton = new JButton("Push");
content.add(newButton);
We can now constrain its
WEST
and
NORTH
edges by tying the edges to the
EAST
and
SOUTH
edges of
button. We use the
putConstraint()
method for the
SpringLayout
object to do this: