Java Reference
In-Depth Information
When the program is run, it will produce the window shown in
Figure 16-1
.
Figure 16-1
The window produced by the
SwingDemo
program
The First Swing Example Line by Line
Because the
SwingDemo
program illustrates several key Swing concepts, we will examine
it carefully, line by line. The program begins by importing the following package:
This
javax.swing
package contains the components and models defined by Swing. For
example, it defines classes that implement labels, buttons, edit controls, and menus. This
package will be included in all programs that use Swing.
Next, the program declares the
SwingDemo
class and a constructor for that class. The
constructor is where most of the action of the program occurs. It begins by creating a
JFrame
, using this line of code:
This creates a container called
jfrm
that defines a rectangular window complete with a title
bar; close, minimize, maximize, and restore buttons; and a system menu. Thus, it creates a
standard, top-level window. The title of the window is passed to the constructor.
Next, the window is sized using this statement:
The
setSize( )
method sets the dimensions of the window, which are specified in pixels. Its
general form is shown here:
void setSize(int
width
, int
height
)