Java Reference
In-Depth Information
Creating a Box
You have three ways to create a Box , offered by one constructor and two static factory methods:
public Box(int direction)
Box horizontalBox = new Box(BoxLayout.X_AXIS);
Box verticalBox = new Box(BoxLayout.Y_AXIS);
public static Box createHorizontalBox()
Box horizontalBox = Box.createHorizontalBox();
public static Box createVerticalBox()
Box verticalBox = Box.createVerticalBox();
Note The Box class is not designed to be used as a JavaBean component. Use of this container within an
IDE can be awkward.
The less frequently used constructor requires a direction for the main axis of the layout
manager. The direction is specified by either of two BoxLayout constants, X_AXIS or Y_AXIS , to
create a horizontal or vertical box, respectively. Instead of manually specifying the direction,
simply create a Box with the desired orientation by using one of the provided factory methods:
createHorizontalBox() or createVerticalBox() .
Filling a horizontal and vertical Box with a JLabel , a JTextField , and a JButton demonstrates
the flexibility of BoxLayout , as shown in Figure 11-1.
Figure 11-1. A horizontal and a vertical box
For the horizontal container, the label and button are at their preferred widths because
their maximum size is the same as their preferred size. The text field uses up the remaining
space.
In the vertical container, the label and button sizes are their preferred size, too, because
their maximum size is still the same as their preferred size. The text field's height fills the height
that the label and button don't use, and its width is as wide as the container.
The source code for creating the screens shown in Figure 11-1 follows in Listing 11-1.
 
Search WWH ::




Custom Search