Java Reference
In-Depth Information
This is done by putting several containers inside a larger container (such as a frame) and
giving each smaller container its own layout manager.
The container to use for these smaller containers is the
panel
, which is created from the
JPanel
class. Panels are containers used to group components together. There are two
things to keep in mind when working with panels:
The panel is filled with components before it is put into a larger container.
n
The panel has its own layout manager.
n
Panels are created with a simple call to the constructor of the
JPanel
class, as shown in
the following example:
JPanel pane = new JPanel();
The layout method is set for a panel by calling the
setLayout()
method on that panel.
The following statements create a layout manager and apply it to a
JPanel
object called
pane
:
FlowLayout flo = new FlowLayout();
pane.setLayout(flo);
Components are added to a panel by calling the panel's
add()
method, which works the
same for panels as it does for some other containers.
11
The following statements create a text field and add it to a
JPanel
object called
pane
:
JTextField nameField = new JTextField(80);
pane.add(nameField);
You'll see several examples of panel use in the rest of today's sample programs.
Card layouts differ from the other layouts because they hide some components from
view. A
card layout
is a group of containers or components displayed one at a time, in
the same way that a blackjack dealer reveals one card at a time from a deck. Each con-
tainer in the group is called a
card
.
If you have used a wizard in an installation program, you have worked with a program
that uses card layout.
The most common way to use a card layout is to use a panel for each card. Components
are added to the panels first, and then the panels are added to the container that is set to
use card layout.