Java Reference
In-Depth Information
You create a grid layout manager, grid , for three rows and four columns, and with horizontal and vertical
gaps between components of 30 and 20 pixels, respectively. You set grid as the layout manager for the
content pane of the application window. You add ten buttons, each with a raised etched border, in the for
loop. The layout manager causes the buttons to be arranged in a rectangular grid arrangement, with gaps
of 30 units between buttons in a row and a gap of 20 units between rows. When you need a rectangular
grid arrangement for your components, the GridLayout manager makes it very easy.
Using a BoxLayout Manager
The javax.swing.BoxLayout class defines a layout manager that arranges components in either a single
row or a single column. You specify whether you want a row-wise or a columnar arrangement when creating
the BoxLayout object. The BoxLayout constructor requires two arguments. The first is a reference to the
container to which the layout manager applies, and the second is a constant that can be either BoxLay-
out.X_AXIS for a row-wise arrangement or BoxLayout.Y_AXIS for a column-wise arrangement.
Components are added from left to right in a row, or from top to bottom in a column. Components in a
given row or column do not spill onto the next row or column when the row or column is full. When you
add more components to a row or column than can be accommodated within the space available, the layout
manager reduces the size of the components or even clips them if necessary to keep them all in a single row
or column. With a row of components, the box layout manager tries to make all the components the same
height and tries to set a column of components to the same width.
The javax.swing.Box container class is particularly convenient when you want to use a box layout be-
cause it has a BoxLayout manager built in. It also has some additional facilities that provide more flexibility
in the arrangement of components than is provided by other containers such as JPanel objects. The Box
constructor accepts a single argument that specifies the orientation as either BoxLayout.X_AXIS or BoxLay-
out.Y_AXIS . The class also has two static methods, createHorizontalBox() and createVerticalBox() ,
that each return a reference to a Box container with the orientation implied.
As I said earlier, a container can contain another container, so you can easily place one Box container
inside another to get any arrangement of rows and columns that you want. Let's try that out.
TRY IT OUT: Boxes Containing Boxes
In this example you create an application that has a window containing a column of radio buttons on the
left, a column of checkboxes on the right, and a row of buttons across the bottom. Here's the code:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class TryBoxLayout {
public static void createWindow(){
Search WWH ::




Custom Search