Java Reference
In-Depth Information
B.3.1 layout managers
A layout manager automatically arranges components of the container. It is
associated with a container by issuing the setLayout command. An example of
using setLayout is the call
The layout man-
ager automatically
arranges compo-
nents of the con-
tainer. A layout
manager is associ-
ated with a con-
tainer by the
setLayout method.
setLayout( new FlowLayout( ) );
Notice that a reference to the layout manager need not be saved. The con-
tainer in which the setLayout command is applied stores it as a private data
member. When a layout manager is used, requests to resize many of the com-
ponents, such as buttons, do not work because the layout manager will choose
its own sizes for the components, as it deems appropriate. The idea is that the
layout manager will determine the best sizes that allow the layout to meet the
specifications.
Think of the layout manager as an expert packer hired by the container
to make the final decisions about how to pack items that are added to the
container.
FlowLayout
The simplest of the layouts is the FlowLayout . When a container is arranged
using the FlowLayout , its components are added in a row from left to right.
When there is no room left in a row, a new row is formed. By default, each
row is centered. This can be changed by providing an additional parameter in
the constructor with the value FlowLayout.LEFT or FlowLayout.RIGHT .
The problem with using a FlowLayout is that a row may break in an awk-
ward place. For instance, if a row is too short, a break may occur between a
JLabel and a JTextField , even though logically they should always remain
adjacent. One way to avoid this is to create a separate JPanel with those two
elements and then add the JPanel into the container. Another problem with the
FlowLayout is that it is difficult to line up things vertically.
The FlowLayout is the default for a JPanel .
The simplest of the
layouts is the
FlowLayout , which
adds components
in a row from left to
right.
BorderLayout
A BorderLayout is the default for objects in the Window hierarchy, such as
JFrame . It lays out a container by placing components in one of five locations.
For this to happen, the add method must provide as a second parameter one of
the strings "North" , "South" , "East" , "West" , and "Center" ; the second parame-
ter defaults to "Center" if not provided (so one single-parameter add will work,
but several add s place items on top of each other). Figure B.5 shows five but-
tons added to a Frame using a BorderLayout . The code to generate this layout is
BorderLayout is the
default for objects
in the Window hier-
archy, such as
JFrame and JDialog .
It lays out a con-
tainer by placing
components in one
of five locations.
 
Search WWH ::




Custom Search