Java Reference
In-Depth Information
RectangleProgram
, containing the application program to calculate the area and peri-
meter of a rectangle, is as follows:
public class
RectangleProgram
extends
JFrame
{
public
RectangleProgram()
//constructor
{
//Necessary code
}
public static void
main(String[] args)
{
//Code for the method main
}
}
In Java,
extends
is a reserved word. The remainder of this section describes the necessary
code to create a window.
An important property of inheritance is that the class (called a subclass) that extends the
definition of an existing class (called a superclass) inherits all the properties of the
superclass. For example, all
public
methods of the superclass can be directly accessed in
the subclass. In our example, the
class
RectangleProgram
is a subclass of the
class
JFrame
, so it can access the
public
methods of the
class
JFrame
. Therefore, to set the
title of the window to
Area and Perimeter of a Rectangle
, you use the method
setTitle
of the
class
JFrame
as follows:
setTitle("Area and Perimeter of a Rectangle");
6
//Line 1
Similarly, the statement:
setSize(400, 300);
//Line 2
sets the window's width to 400 pixels and its height to 300 pixels. (A pixel is the smallest
unit of space on your screen. The term pixel stands for picture element.) Note that since the
pixel size depends on the current monitor setting, it is impossible to predict the exact
width and height of a window in centimeters or inches.
Next, to display the window, you must invoke the method
setVisible
. The following
statement accomplishes this:
setVisible(
true
);
//Line 3
To terminate the application program when the user closes the window, use the follow-
ing statement (as described in Table 6-1):
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Line 4
The statements in Lines 1, 2, 3, and 4 will be placed in the constructor (that is, in the
method whose heading is
public
RectangleProgram()
). Thus, you can write the
constructor as follows:
Search WWH ::
Custom Search