Java Reference
In-Depth Information
TrySpringLayout.java
When you compile and run this, you should get a window with the buttons laid out as shown in
Figure
17-35
.
How It Works
You first create a variable that stores a reference to a
SpringLayout.Constraints
object and array to
hold references to
JButton
objects:
JButton[] buttons = new JButton[6]; // Array to store
buttons
SpringLayout.Constraints constr = null;
You create and add six buttons to the content pane of the window in a loop:
for(int i = 0 ; i < buttons.length ; ++i) {
buttons[i] = new JButton("Press " + (i+1));
content.add(buttons[i]); // Add a Button to
content pane
}
As each button is added to the container, the layout manager applies the constraints to the height and
width of the container that I discussed earlier. Unless these are overridden because the component is
overconstrained, these constraints adjust the size of the button based on the minimum, maximum, and
preferred sizes for the component.
After adding six buttons to the content pane of the window, you define two
Spring
objects that you use
to position the first button relative to the container:
Spring xSpring = Spring.constant(5,15,25); // x constraint for
1st button