Java Reference
In-Depth Information
way of creating windows in this textbook. The reader, however, can easily modify the code
to use the event dispatch thread as the above code shows.
Next, let us concentrate on the
BreakoutFrame
class. A possible implementation is
shown next.
class
BreakoutFrame
extends
JFrame
{
public static final
int
HEIGHT = 600;
public static final
int
WIDTH = 488;
public static final
int
LOCATION X = 50;
public static final
int
LOCATION Y = 100;
public
BreakoutFrame ()
{
setDefaultCloseOperation(JFrame.EXITON CLOSE) ;
setLocation(LOCATIONX, LOCATION Y) ;
setSize(WIDTH, HEIGHT);
setResizable(
false
);
}
}
Note that the first line of the constructor does not call the constructor of the super
class. Therefore, the empty constructor of the
JFrame
class is automatically called. As a
consequence, the above code is equivalent to the following code.
class
BreakoutFrame
extends
JFrame
{
public static final
int
HEIGHT = 600;
public static final
int
WIDTH = 488;
public static final
int
LOCATION X = 50;
public static final
int
LOCATION Y = 100;
public
BreakoutFrame ()
{
super
() ;
setDefaultCloseOperation(JFrame.EXITON CLOSE) ;
setLocation(LOCATIONX, LOCATION Y) ;
setSize(WIDTH, HEIGHT);
setResizable(
false
);
}
}
The actual window is created by the call
super()
. All the methods that are invoked in the
constructor (i.e.,
setDefaultCloseOperation
,
setLocation
,
setSize
,and
setResizable
)
belong to the
JFrame
class (or its superclasses). Since the
BreakoutFrame
classdoesnot
contain these methods, Java automatically searches for the methods in the
JFrame
super-
class.
The
setDefaultCloseOperation
method defines the behavior of the close button of
the window. There are four possible actions, which are specified by constants in the
JFrame
class. The constant
EXIT ON CLOSE
means that the program will terminate when the window
is closed. The constant
HIDE ON CLOSE
means that the window will be hidden, but the
program will not terminate. If we want to display the window later, then we need to call
the
setVisible
method again. The constant
DISPOSE ON CLOSE
describes the behavior
where the window is destroyed, but the program is not terminated. Lastly, the constant
DO NOTHING ON CLOSE
means that pressing the button that closes the window will have no
effect.
Before we explain how the
setLocation
and
setSize
methods work, let us first describe
the architecture of a computer screen. The screen of a computer is divided into pixels. The
actual resolution of the screen can be changed, where, for example, 1366 by 768 pixels is a