Java Reference
In-Depth Information
Figure 10-8.
BoxLayout example, before and after resizing
Creating a BoxLayout
BoxLayout
has a single constructor:
public BoxLayout(Container target, int axis)
The constructor takes two arguments. The first argument is the container with which this
instance of the layout manager is to be associated, and the second is the layout direction. Valid
directions are
BoxLayout.X_AXIS
for a left-to-right layout and
BoxLayout.Y_AXIS
for a top-to-
bottom layout.
■
Caution
Trying to set the axis to something other than the equivalent value of the two constructor
constants will throw an
AWTError
. If the layout manager is associated with a container that isn't the
container passed in to the constructor, an
AWTError
will be thrown when the layout manager tries to lay
out the other (that is, wrong) container.
Once you create a
BoxLayout
instance, you can associate the layout manager with a
container as you would with any other layout manager.
JPanel panel = new JPanel();
LayoutManager layout = new BoxLayout (panel, BoxLayout.X_AXIS);
panel.setLayout(layout);
Unlike all the other system-provided layout managers, a
BoxLayout
and container are bound
together in two directions, from manager to container as well as from container to manager.
■
Tip
The
Box
class, described in Chapter 11, lets you create a container and set its layout manager to
BoxLayout
all in one step.