Java Reference
In-Depth Information
Creating an Interface
The first step in creating a Swing application is to create a class that represents the
graphical user interface. An object of this class serves as a container that holds all the
other components to be displayed.
In many projects, the main interface object is either a simple window (the
JWindow
class)
or a more specialized window called a
frame
(the
JFrame
class).
A window is a container that can be displayed on a user's desktop. A simple window
does not have a title bar; Maximize, Minimize, or Close buttons; or other features you
see on most windows that open in a graphical operating system. In Swing, windows that
do have these features are called
frames
.
9
In a graphical environment such as Windows or Mac OS, users expect to have the ability
to move, resize, and close the windows of programs that they run. The main place a sim-
ple window, rather than a frame, turns up is when programs are loading—there is some-
times a title screen with the program's name, logo, and other information.
One way to create a graphical Swing application is to make the interface a subclass of
JFrame
, as in the following class declaration:
public class FeedReader extends JFrame {
// ...
}
The constructor of the class should handle the following tasks:
Call a superclass constructor to give the frame a title and handle other setup proce-
dures.
n
Set the size of the frame's window, either by specifying the width and height in
pixels or by letting Swing choose the right size.
n
Decide what to do if a user closes the window.
n
Display the frame.
n
The
JFrame
class has two constructors:
JFrame()
and
JFrame(
String
)
. One sets the
frame's title bar to the specified text, and the other leaves the title bar empty. You also
can set the title by calling the frame's
setTitle(
String
)
method.
The size of a frame can be established by calling the
setSize(
int, int)
method with the
width and height as arguments. The size of a frame is indicated in pixels, so if you called
setSize(650, 550)
, the frame would take up most of a screen at 800
Ă—
600 resolution.