Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Using Layout Managers 191

TheBoxLayoutManager


Another handy layoutmanager, BoxLayoutin the javax.swingpackage,
makes it possible to stack components in a single row horizontally or
vertically.


To employ this layout, create a panel to hold components, and then create
a layout manager with two arguments:


. The component to organize in box layout
. The value BoxLayout.Y_AXISfor vertical alignment and
BoxLayout.X_AXISfor horizontal alignment


Here’s code to stack the Crisiscomponents:


JPanel pane = new JPanel();
BoxLayout box = new BoxLayout(pane, BoxLayout.Y_AXIS);
pane.setLayout(box);
pane.add(panicButton);
pane.add(dontPanicButton);
pane.add(blameButton);
pane.add(mediaButton);
pane.add(saveButton);
add(pane);


Figure 14.4 shows how this turns out.


Separating Components with Insets


As you are arranging components within a container, you can move com-
ponents away from the edges of the container using Insets, an object that
represents the border area of a container.


The Insetsclass, which is part of the java.awtpackage, has a constructor
that takes four arguments: the space to leave at the top, left, bottom, and
rightof the container. Each argument is specified using pixels, the same
unit of measure employed when defining the size of a frame.


FIGURE 14.3
Arranging components using
border layout.

FIGURE 14.4
Stacking components using box
layout.
Free download pdf