Java Reference
In-Depth Information
How It Works
After adding six buttons to the content pane of the window, we define two Spring objects that we will
use to position the first button:
Spring xSpring = Spring.constant(5,15,25); // x constraint for 1st button
Spring ySpring = Spring.constant(10,30, 50); // y constraint for first button
We also define a spring we will use to determine the width of each button:
Spring wSpring = Spring.constant(30,80,130); // Width constraint for buttons
We then set the location of the first button relative to the container:
// Connect x,y for first button to left and top of container by springs
SpringLayout.Constraints buttonConstr = layout.getConstraints(buttons[0]);
buttonConstr.setX(xSpring);
buttonConstr.setY(ySpring);
This fixes the first button. We can define the positions of each the remaining buttons relative to its
predecessor. We do this by adding constraints between the NORTH and WEST edges of each button and
the SOUTH and EAST edges of its predecessor. This is done in the for loop after setting the width and
height constraints for each button :
// Set width and height of buttons and hook buttons together
for(int i = 0 ; i< buttons.length ; i++) {
buttonConstr = layout.getConstraints(buttons[i]);
buttonConstr.setHeight(ySpring); // Set the button height constraint
buttonConstr.setWidth(wSpring); // and its width constraint
// For buttons after the first tie W and N edges to E and N of predecessor
if(i>0) {
layout.putConstraint(SpringLayout.WEST,buttons[i],
xSpring,SpringLayout.EAST, buttons[i-1]);
layout.putConstraint(SpringLayout.NORTH,buttons[i],
ySpring,SpringLayout.SOUTH, buttons[i-1]);
} // end if
} // end for
This places each component after the first relative to the bottom right corner of its predecessor so the
buttons are laid out in a cascade fashion.
Relating the Container Size to the Components
Of course, the size of the application window in our example is independent of the components within it. If
you resize the window the springs have no effect. If you call pack() for the aWindow object before calling
its setVisible() method, the window will shrink to a width and height just accommodating the title bar so
you won't see any of the components. This is because SpringLayout does not adjust the size of the
container by default so the effect of pack() is as though the content pane was empty.
Search WWH ::




Custom Search