Java Reference
In-Depth Information
Understanding Constraints
The top, bottom, left, and right edges of a component are referred to by their compass points, north,
south, west, and east. When you need to refer to a particular edge in your code - for setting a constraint
for instance, you use constants that are defined in the SpringLayout class, NORTH , SOUTH , WEST , and
EAST respectively.
Each constraint is defined
by a
Spring
Object
Position x,y
NORTH
X constraint
Component
SOUTH
Width constraint
Constraints on a Component in a SpringLayout
As the diagram shows, the position of a component is determined by a horizontal constraint on the x-
coordinate of the component and a vertical constraint on the y-coordinate. These obviously also
determine the location of the WEST and NORTH edges of the component, since the position determines
where the top-left corner is located. The width and height are determined by horizontal constraints that
relate the position of the EAST and SOUTH edges to the positions of the WEST and NORTH edges
respectively. Thus the constraints on the positions of the EAST and SOUTH edges are determined by
constraints that are derived from the others, as follows:
EAST-constraint = X-constraint + width-constraint
SOUTH-constraint = Y-constraint + height-constraint
You can set the X, Y, width, and height constraints independently as we shall see in a moment, and you can
also set a constraint explicitly for any edge. If you set a constraint on the SOUTH or EAST edges of a
component, the Y or X constraint will be adjusted if necessary to ensure the relationships above still hold.
Defining Constraints
The Spring class in the javax.swing package defines an object that represents a constraint. A
Spring object is defined by three integer values that relate to the notional length of the spring: the
minimum value, the preferred value, and the maximum value. A Spring object will also have an
actual value that lies between the minimum and the maximum, and that will determine the location of
the edge to which it applies. You can create a Spring object like this:
Spring spring = Spring.constant(10, 30, 50); // min=10, pref=30, max=50
Search WWH ::




Custom Search