Each of the calls cp.add(…) in the constructor places a component (the first
argument of the call) in one of these five areas; the second argument, a constant
of class BorderLayout , says where to put it. The diagram below shows the five
areas of the content pane when using a BorderLayout manager.
WEST CENTER EAST
The east contains a JButton (see Fig. 17.2). The argument of the call to the
JButton constructor is the text to display on the button. Section 17.4 discusses
how to make your program respond to a button click.
In the south and west of the content pane are JLabel s, which are one-line
display areas for text strings and images. Again, the argument of the constructor
is the text to display. JLabel s do not respond to mouse clicks or other events.
In the north is a JTextField , which is a one-line area into which the user
can type. The constructor arguments are the initial text of the text field and the
approximate width of the text field, in characters.
In the center is a JTextArea , which is a multi-line typing area. The con-
structor arguments are the initial text of the text area, the number of lines to dis-
play, and the approximate width of the text field, in characters.
Basically, that is all there is to placing components in a JFrame . You do not
have to add a component in each area. For example, if no component is placed
in the east, the east part takes up no room.
Method pack of the constructor causes the components in the window to be
resized to fit together, using the “preferred sizes” of the components. If pack is
not called, the sizes of the components are unpredictable.
Even in the packed version, the center text-area is much wider than ten char-
acters! This is because the north text field is so wide; the content pane is layed
out so that each component gets at least as much room as it requested.
In the next section, we describe most of the kinds of components that can be
placed in a JFrame .
Some older programs use the old class Frame of package java.awt instead
of JFrame . (Actually, JFrame is a subclass of Frame .) In a Frame , the compo-
nents are added to the JFrame , and not to its content pane, so local variable cp
and the prefix “ cp. ” on all calls to add would be removed.
shows what the
like if it is not
We give details about frequently used components, each of which is a subclass
of class JComponent . To learn how to “listen” to a component, for example, to
respond to a click of a mouse, see Sec. 17.4.