Java Reference
In-Depth Information
ViewportLayout Class
The
ViewportLayout
manager is used by the
JViewport
class, a container class (to be described
in Chapter 11). The
JViewport
is also used within the
ScrollPaneLayout
/
JScrollPane
combination.
Like
ScrollPaneLayout
, the
ViewportLayout
manager is closely tied to its component,
JViewport
in this case, and isn't usable outside the component, except in a subclass. In addition, the
JViewport
class is rarely used outside a
JScrollPane
. The
ViewportLayout
manager will be discussed
in the context of its container,
JViewport
, in Chapter 11.
SpringLayout Class
The newest addition to the Java layout manager front is the
SpringLayout
manager, added with
the J2SE 1.4 release. This allows you to attach “springs” to components so that they are laid out
relative to other components. For instance, with
SpringLayout
, you can say that a button
appears attached to the right border, no matter what size a user makes the screen.
The
SpringLayout
manager relies on
SpringLayout.Constraints
for the component
constraints. This works similarly to the
GridBagConstraints
class that complements the
GridBagLayout
manager. Each component added to the container can have an attached
SpringLayout.Constraints
. Therein lies the end to the similarities between these two types
of constraints.
You usually don't need to add the component with the constraints. Instead, you can add
the component, and then typically attach the constraints separately. There is nothing stopping
you from adding the constraints with the component, but
SpringLayout.Constraints
is not a
simple class. It is a collection of
Spring
objects, each a different constraint on the component.
You need to add each
Spring
constraint separately to
SpringLayout.Constraints
. You do this
by setting specific constraints on an edge of the component. Using the four
SpringLayout
constants of
EAST
,
WEST
,
NORTH
, and
SOUTH
, you call the
setContraints(String edge, Spring
spring)
method of
SpringLayout.Constraints
, where the
String
is one of the constants.
For instance, if you want to add a component in the top left of a container, you can set up
two springs of a constant size, combine them together, and add the component to the
container with the combined set, as shown here:
Component left = ...;
SpringLayout layout = new SpringLayout();
JPanel panel = new JPanel(layout);
Spring xPad = Spring.constant(5);
Spring yPad = Spring.constant(25);
SpringLayout.Constraints constraint = new SpringLayout.Constraints();
constraint.setConstraint(SpringLayout.WEST, xPad);
constraint.setConstraint(SpringLayout.NORTH, yPad);
frame.add(left, constraint);