Java Reference
In-Depth Information
Putting borders around JComponents
. This is an advanced topic. There is a way to put a bor-
der around any
JComponent
, like a
JButton
or a
JPanel
. You cannot put a bor-
der around a
Box
this way, but you get that effect by adding the
Box
as the only
component of a
JPanel
and then putting a border around the
JPanel
.
A footnote at the bottom of lesson page 17-3 of the CD shows you how to
put borders around
JComponents
and gives several examples.
17.3
Containers and layout managers
Class
JFrame
is a subclass of class
Container
, which means that it can contain
components like buttons and labels.
JFrame
, with a
BorderLayout
manager,
may seem rather limited because it can contain only five components —in the
east, north, west, south, and center.
We introduce two other containers, the
Jpanel
and the
Box
, which have lay-
out managers
FlowLayout
and
BoxLayout
, respectively. Instances of
JPanel
and
Box
can be added as components to a
JFrame
—or even to another
JPanel
or
Box
. This nesting of containers allows us to construct a
JFrame
whose layout
is quite complex and that can contain any number of components.
There are other layout managers, e.g.
CardLayout
,
GridBagLayout
,
GridLayout
, and
OverlayLayout
. We do not discuss them.
import
java.awt.*;
import
javax.swing.*;
/**
An instance has labels in the north and south and a
JPanel
with four buttons in the center
*/
public class
PanelDemo
extends
JFrame {
JPanel p=
new
JPanel();
/**
Constructor: an invisible frame with title
t
, 2 labels, and a 4-button
JPanel */
public
PanelDemo(String t) {
super
(t);
p.add(
new
JButton("0"));
p.add(
new
JButton("1"));
p.add(
new
JButton("2"));
p.add(
new
JButton("3"));
Container cp= getContentPane();
cp.add(
new
JLabel("north"),BorderLayout.NORTH);
cp.add(
new
JLabel("south"),BorderLayout.SOUTH);
cp.add(p,BorderLayout.CENTER);
pack();
}
}
Figure 17.10:
Class
PanelDemo
Search WWH ::
Custom Search