Frames let you
separate different functions or data into different windows. For
instance a painting application may have several different pictures
in varying states of completion open in different windows. Or it
may have only one picture but a separate window might contain a
tool palette to select different brushes or colors. Each of these
windows would be a Frame
.
Everything you need to create and work with frames is contained
in the java.awt.Frame
class. To create a new frame
without a title bar use the Frame()
constructor with
no arguments.
Frame f = new Frame();
More commonly you'll want to name the frame by passing a string that specifies the window's title to the constructor:
Frame f = new Frame("App Window");
Frames inherit from java.awt.Container
so you can add
components to a frame. Unlike panels and applets, the default
LayoutManager
for a frame is
BorderLayout
, not FlowLayout
. However you can
change this using the frame's setLayout()
method like
this:
f.setLayout(new FlowLayout());
Frames inherit from java.awt.Component
so they have
paint()
and update()
methods. If you want
to draw in the frame and process events manually like you did in
applets, just create a subclass of Frame
and add
listener objects to it. Almost everything you did in those chapters
with a user-defined subclass of java.awt.Applet
can
also be done with a user-defined subclass of
java.awt.Frame
.
However most of the time you'll prefer to use components. To add
a component to a frame call the frame's add()
method
just as you would call an applet's add()
method. The
only difference is that you may often call the add()
method from outside the Frame
class so you'll need to
prefix add with a variable that points to the frame and the member
operator .
In other words given a Frame
f
, you need to call
f.add(new Button("OK");
rather than simply
this.add(new Button("OK"));
Of course this depends on what class you're inside of when you call
add()
. If you're calling add()
from one
of the Frame
subclass's own methods you won't need to
do this.
Since the default layout for a frame is BorderLayout
, you should specify whether you want the
component added to the North, South, East, West or Center. Here's
how you'd add a centered label to the center of Frame
f
:
f.add(BorderLayout.CENTER, new Label("This is a frame", Label.CENTER));