Java Reference
In-Depth Information
in a
JFrame
. Thus, one of the main functions of
JPanel
objects is to subdivide a
JFrame
(or other container) into different areas.
For example, when you use a
BorderLayout
manager, you can place components
in each of the five locations
BorderLayout.NORTH
,
BorderLayout.SOUTH
,
BorderLayout.EAST
,
BorderLayout.WEST,
and
BorderLayout.CENTER.
But what if
you want to put two components at the bottom of the screen in the
BorderLayout.SOUTH
position? To do this, you would put the two components in a panel and then place the
panel in the
BorderLayout.SOUTH
position.
You can give different layout managers to a
JFrame
and to each panel in the
JFrame
.
Because you can add panels to other panels and each panel can have its own layout manager,
this enables you to produce almost any kind of overall layout of the items in your GUI.
For example, if you want to place two buttons at the bottom of your
JFrame
GUI,
you might add the following to the constructor of your
JFrame
GUI:
setLayout(
new
BorderLayout());
JPanel buttonPanel =
new
JPanel();
buttonPanel.setLayout(
new
FlowLayout());
JButton firstButton =
new
JButton("One");
buttonPanel.add(firstButton);
JButton secondButton =
new
JButton("Two");
buttonPanel.add(secondButton);
add(buttonPanel, BorderLayout.SOUTH);
The next Programming Example makes use of panels within panels.
EXAMPLE:
A Tricolor Built with Panels
When first run, the GUI defined in Display 17.11 looks as shown in the first view.
The entire background is light gray, and there are three buttons at the bottom of the
GUI labeled
"Green"
,
"White"
, and
"Gray"
. If you click any one of the buttons, a
vertical stripe with the color written on the button appears. You can click the buttons
in any order. In the last three views in Display 17.11, we show what happens if you
click the buttons in left-to-right order.
The green, white, and gray stripes are the
JPanes
named
greenPanel
,
whitePanel
, and
grayPanel.
At first the panels are not visible because they are
all light gray, so no borders are visible. When you click a button, the corresponding
panel changes color and so is clearly visible.
Notice how the action listeners are set up. Each button registers the
this
parameter as a listener, as in the following line:
redButton.addActionListener(
this
);
Because this line appears inside of the constructor for the class
PanelDemo,
the
this
parameter refers to
PanelDemo,
which is the entire GUI. Thus, the entire
JFrame
(continued)