Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^376) | Event-Driven Input and Output


8.1 Frames


The type of window that we use in this text is called a frame, and it is implemented in Java
by a class called JFrame. A frame has all of the features that you are used to seeing in a win-
dow on a personal computer: the ability to change size, to be closed, to be turned into an icon
(a small pictorial representation of the window), and so on.
Our example applications won’t support all the features of a JFrame. Instead, we focus on
those features that illustrate the essential concepts of GUI programming. Supporting extra
features would make our code longer, and the extra code won’t illustrate new principles but
just add more of the same kinds of method calls. Once you understand the underlying con-
cepts of the GUI, you can easily read the class documentation and add support for more
window features as you wish.
To use a frame for output in Java, our code must perform four steps:

1.Import classes and declare fields.
2.Instantiate frame objects and specify some of their properties.
3.Put display objects into the frame.
4.Make the frame visible on the screen.

Import Classes and Declare Fields


The first of these steps breaks down into three parts.

1.Import the package containing the JFrameclass.
2.Declare a variable of the class JFrame.
3.Declare a variable of the class Container.

The JFrameclass is contained in the swingpackage within a larger package called javax.
So we write the following importstatement:

importjavax.swing.*; // Supplies JFrame class for output display

We need to declare both a JFramevariable and a Containervariable. Here’s why. A JFrameob-
ject has two parts. The window frame contains the “close” button and other components. The
content pane represents the main area inside the frame where we place information to be
displayed. (See Figure 8.1.) The content pane is an object of the class Container, so we must
provide a variable of this class so that we can refer directly to it.
Suppose that our JFrameis to be called outputFrameand we want to refer to its content pane
as outputPane. Then we would write the following declarations:

JFrame outputFrame; // Declare a variable of class JFrame
Container outputPane; // Declare a variable of class Container
Free download pdf