Java Reference
In-Depth Information
Let's review the important points introduced in this section:
The preceding program has exactly one class:
RectangleProgramOne
.
The
contains
the
constructor
class
RectangleProgramOne
RectangleProgramOne
and the
main
method.
You created the new
class
RectangleProgramOne
by extending the
existing class,
JFrame
. Therefore,
JFrame
is the superclass of
RectangleProgramOne
, and
RectangleProgramOne
is a subclass of
JFrame
.
Whenever there is a superclass-subclass relationship, the subclass inherits all
the data members and methods of the superclass. The methods
setTitle
,
setSize
,
setVisible
,and
setDefaultCloseOperation
are methods
of the
class
JFrame
, and these methods can be inherited by its subclasses.
The next few sections describe how to create GUI labels, text fields, and buttons, which
can all be placed in the content pane of a window. Before you can place GUI compo-
nents in the content pane, you must learn how to access the content pane.
If you can visualize
JFrame
as a window, think of the content pane as the inner area of the
window (below the title bar and inside the border). The
class
JFrame
has the method
getContentPane
that you can use to access the content pane of the window. However, the
class
JFrame
does not have the necessary tools to manage the components of the content
pane. The components of the content pane are managed by declaring a reference variable of
the
Container
type and then using the method
getContentPane
, as shown next.
Consider the following statements:
Container pane;
//Line 1
pane = getContentPane();
//Line 2
The statement in Line 1 declares
pane
to be a reference variable of the
Container
type.
The statement in Line 2 gets the content pane of the window as a container, that is, the
reference variable
pane
now points to the content pane. You can now access the content
pane to add GUI components to it by using the reference variable
pane
.
The statements in Lines 1 and 2 can be combined into one statement:
Container pane = getContentPane();
//Line 3
If you look back at Figure 6-2, you will see that the labels, text fields, and buttons are
arranged in five rows and two columns. To control the placement of GUI components in
the content pane, you set the layout of the content pane. The layout used in Figure 6-2 is
called the grid layout. The
class
Container
provides the method
setLayout
,as
described in Table 6-2, to set the layout of the content pane. To add components such
as labels and text fields to the content pane, you use the method
add
of the
class
Container
, which is also described in Table 6-2.
Search WWH ::
Custom Search