Java Reference
In-Depth Information
This 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 example, you could add another button to the container like this:
JButton newButton = new JButton("Push");
content.add(newButton);
You can now constrain its WEST and NORTH edges by tying the edges to the EAST and SOUTH edges of the
button component that you added to the container previously. You use the putConstraint() method for
the SpringLayout object to do this:
SpringLayout.Constraints newButtonConstr = layout.getConstraints(newButton);
layout.putConstraint(SpringLayout.WEST,
newButton,
xSpring,
SpringLayout.EAST,
button);
The first two arguments to the putConstraint() method for the layout object are the edge specification
and a reference to the dependent component, respectively. The third argument is a Spring object defining
the constraint. The fourth and fifth arguments specify the edge and a reference to the component to which the
dependent component is anchored. Obviously, because constraints can only be horizontal or vertical, both
edges should have the same orientation. There is an overloaded version of the putConstraint() method
for which the third argument is a value of type int that defines a fixed distance between the edges.
Let's look at a simple example using a SpringLayout object as the layout manager.
TRY IT OUT: Using a SpringLayout Manager
Here's the code for an example that displays six buttons in a window:
import javax.swing.*;
import java.awt.*;
public class TrySpringLayout {
public static void createWindow(){
JFrame aWindow = new JFrame("This is the Window Title");
Toolkit theKit = aWindow.getToolkit();
// Get the
window toolkit
Dimension wndSize = theKit.getScreenSize();
// Get screen
size
// Set the position to screen center & size to half screen size
aWindow.setBounds(wndSize.width/4, wndSize.height/4,
// Position
Search WWH ::




Custom Search