Java Reference
In-Depth Information
Try It Out - Centering a Window
Here's the code:
import javax.swing.JFrame;
import java.awt.Point;
import java.awt.GraphicsEnvironment;
public class TryWindow
// The window object
static JFrame aWindow = new JFrame("This is the Window Title");
public static void main(String[] args) {
Point center =
GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
int windowWidth = 400;
int windowHeight = 150;
// set position and size
aWindow.setBounds(center.x-windowWidth/2, center.y-windowHeight/2,
windowWidth, windowHeight);
aWindow.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
aWindow.setVisible(true); // Display the window
}
}
When you execute this you should see the window displayed centered on your screen.
How It Works
This uses the coordinates of the point returned by the getCenterPoint() method to position the window.
We calculate the position of the top-left corner of the application window by subtracting half the window
width and half the height from the x and y coordinates of the screen center point, respectively.
Points and Rectangles
Let's digress briefly into more detail concerning the Point and Rectangle classes before continuing
with the Component class methods, as they are going to come up quite often. Both these classes are
defined in java.awt . You will find many of the methods provided by the Point and Rectangle
classes very useful when drawing in a window. Entities displayed in a window will typically have
Rectangle objects associated with them that define the areas within the window that they occupy.
Point objects are used in the definition of other geometric entities such as lines and circles, and to
specify their position in a window.
Note that neither Point nor Rectangle objects have any built-in representation on the screen. They
aren't components; they are abstract geometric entities. If you want to display a rectangle you have to
draw it. We will see how to do this in Chapter 13.
Point Objects
As we said, the Point class defines a point by two public data members of type int , x and y . Let's
look at the methods that the class provides.
Search WWH ::




Custom Search