Java Graphics  «Prev 

Java's Graphics coordinate system

Java relies on a graphics coordinate system to determine how graphics are drawn.
The Java graphics coordinate system has an X-axis that increases to the right and a Y-axis that increases down. The origin of this coordinate system is located in the upper left corner of the graphics context to which you are drawing, which is often the upper left corner of an applet window.
This results in all applet graphics being drawn relative to the upper left corner of the applet window.

Position

A component's position is specified in x and y coordinates. In Java, all coordinates are measured in pixels relative to an absolute coordinate space that has the top left-hand corner of the screen as the origin (x = 0, y = 0) and where x coordinates increase as you move from left to right and y coordinates increase as you move toward the bottom of the screen. The coordinates of a JFrame that sits directly on the desktop are, as you have already seen, given relative to the top left-hand corner of the screen and are therefore absolute values. However, a typical application is made up of many components that reside inside the frame. It is not convenient to specify the coordinates of these components as absolute values, because they would all have to be adjusted if the frame s position were changed.

Nested Component

To avoid this problem, the position of a nested component is measured relative to that of its parent. As the parent moves, its coordinates may change, but those of its children will still be correct. To calculate the absolute coordinates of any child component, you simply add its coordinates to those of its parent. You can retrieve the coordinates of a component relative to its parent using either the getLocation or getBounds methods of Component. The first of these returns a Point object that contains only the components x and y coordinates, while the second returns a Rectangle containing both the position and the size of the component. These methods work equally well for both a top-level frame and a component mounted on a container.