Java Reference
In-Depth Information
That doesn't look too complicated, but it gets more difficult when you need to add the next
component, either to the right of the first or below it. You can't just say to add the component
n
pixels over. You must actually add the padding to the edge of the earlier component. To find
the edge of the earlier component, you ask the layout manager with
getConstraint()
, passing
in the edge you want and the component, as in
layout.getConstraint(SpringLayout.EAST, left)
,
to get the location of the right edge of the first component. From that location, you can add in
the necessary padding and attach it to the edge of the other component, as shown here:
Component right = ...;
Spring rightSideOfLeft = layout.getConstraint(SpringLayout.EAST, left);
Spring pad = Spring.constant(20);
Spring leftEdgeOfRight = Spring.sum(rightSideOfLeft, pad);
constraint = new SpringLayout.Constraints();
constraint.setConstraint(SpringLayout.WEST, leftEdgeOfRight);
constraint.setConstraint(SpringLayout.NORTH, yPad);
frame.add(right, constraint);
This works perfectly well, but it gets tedious as the number of components increases. To
eliminate the in-between steps, you can add the components without the constraints, and
then add each separately, connecting the components via the
putConstraint()
method of
SpringLayout
.
public void putConstraint(String e1, Component c1, int pad, String e2,
Component c2)
public void putConstraint(String e1, Component c1, Spring s, String e2,
Component c2)
Here, instead of asking for the edge and adding in the padding yourself, the
putConstraint()
call combines the tasks for you. To demonstrate, the following snippet adds the same component
constraints to the right component as the previous one, but using
putConstraint()
instead of
using
SpringLayout.Constraints
directly:
Component left = ...;
Component right = ...;
SpringLayout layout = new SpringLayout();
JPanel panel = new JPanel(layout);
panel.add(left);
panel.add(right);
layout.putConstraint(SpringLayout.WEST, left, 5, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, left, 25, SpringLayout.NORTH, panal);
layout.putConstraint(SpringLayout.NORTH, right, 25, SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, right, 20, SpringLayout.EAST, left);
To help you visualize the use of
SpringLayout
, Sun has a tool available from
https://
bean-builder.dev.java.net/
called The Bean Builder. The tool is primarily intended to be used
when working with JavaBean components, but it works well to see
SpringLayout
in action.
Figure 10-20 shows what the tool looks like on startup through Java WebStart.