Java Reference
In-Depth Information
You obtain the
Toolkit
object,
theKit
, by calling the
getToolkit()
method for the
JFrame
object,
aWindow
. This object represents the environment on your computer, so it encapsulates all the properties
and capabilities of that environment as far as Java is concerned, including the screen resolution and size.
NOTE
Youcan'tcreatea
Toolkit
objectdirectlybecause
Toolkit
isan
abstract
class. There is only one
Toolkit
object in an application — the one that you get a
reference for when you call
getToolkit()
for a component.
The
getScreenSize()
method that is a member of the
Toolkit
object returns an object of type
Dimen-
sion
containing data members
width
and
height
. These hold the number of pixels for the width and
height of your primary display. You use these values to set the coordinates for the position of the window
and the width and height of the window through the
setBounds()
method. Of course, you can use this
approach to position the application window anywhere relative to the screen.
This is not the only way of centering a window. A
java.awt.GraphicsEnvironment
object contains
information about the graphics devices attached to a system, including the display — or displays in sys-
tems with more than one. You can obtain a reference to a
GraphicsEnvironment
object that encapsulates
information about the graphics devices on the local machine by calling the static
getLocalGraphicsEn-
vironment()
method in the
GraphicsEnvironment
class, like this:
GraphicsEnvironment localGE =
GraphicsEnvironment.getLocalGraphicsEnvironment();
This requires the following import:
import java.awt.GraphicsEnvironment;
You can now call this object's
getCenterPoint()
method to obtain a
java.awt.Point
object contain-
ing the coordinates of the center of the screen:
Point center = localGE.getCenterPoint();
You can now pass the coordinates of
center
to the
setBounds()
method:
aWindow.setBounds(center.x-wndSize.width/2, center.y-
wndSize.height/2,
wndSize.width,
wndSize.height);
An even simpler mechanism is to call the
setLocationRelativeTo()
method that a
JFrame
object in-
herits from the
Window
class. This method centers the window at the center of another component that
you pass as the argument. If the argument is
null
, the method centers the window relative to the primary
display.
You could try this with a variation on the original version of the example.