Java Reference
In-Depth Information
own. Their power becomes apparent when combined, however. For example, you
can use a GridLayout to arrange 10 buttons into two columns within a container,
and then use a BorderLayout to position those two columns against the left edge
of another container.
The following sections demonstrate all the important layout managers, using a
short example and a screen shot of the layout produced by the example. The fig-
ures are produced using the ShowComponent class from Example 10-1; you can use
this program to experiment with the examples yourself. Pay particular attention to
the way the layouts change when you resize the window.
FlowLayout
The FlowLayout layout manager arranges its children like words on a page: from
left to right in a row and top to bottom. When there is not enough space remain-
ing in the current row for the next component, the FlowLayout “wraps” and places
the component in a new row. When you create a FlowLayout , you can specify
whether the rows should be left-justified, centered, or right-justified. You can also
specify the amount of horizontal and vertical space the layout manager leaves
between components. FlowLayout makes no attempt to fit its components into the
container; it leaves each component at its preferred size. If there is extra space,
FlowLayout leaves it blank. If there is not enough room in the container, some
components simply do not appear. Note that FlowLayout is the default layout man-
ager for JPanel containers. If you do not specify a different layout manager, a
panel uses a FlowLayout that centers its rows and leaves five pixels between com-
ponents, both horizontally and vertically.
Example 10-3 is a short program that arranges buttons using a FlowLayout layout
manager; Figure 10-3 shows the resulting output.
Figure 10•3. Components laid out with a FlowLayout
Example 10•3: FlowLayoutPane.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import javax.swing.*;
Search WWH ::




Custom Search