Java Reference
In-Depth Information
// The window object
static JFrame aWindow = new JFrame("This is the Window Title");
public static void main(String[] args) {
Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to half screen size
aWindow.setBounds(wndSize.width/4, wndSize.height/4, // Position
wndSize.width/2, wndSize.height/2); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
aWindow.setVisible(true); // Display the window
}
}
If you try this example, you should see the application window centered on your display with a width
and height of half that of the screen.
How It Works
The Toolkit object, theKit , is obtained 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 that you can't create a Toolkit object directly since Toolkit is an 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
Dimension containing data members width and height . These hold the number of pixels for the
width and height of your display. We 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.
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 systems 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 getLocalGraphicsEnvironment() method, like this:
GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();
You can now call this object's getCenterPoint() method to obtain a Point object containing the
coordinates of the center of the screen:
Point center = localGE.getCenterPoint();
We could try this with a variation on the original version of TryWindow.
Search WWH ::




Custom Search