Java Reference
In-Depth Information
GUI Coordinates
All components and containers have a size and location, which is denoted in pixels. A pixel
is a relative unit of measurement based on the settings of the user's screen. The pixels cre-
ate a coordinate system, with the upper-left corner of the screen as the origin (0,0). Any
point on the screen can be represented as an (x,y) value, where x is the number of pixels
to the right of the origin, and y is the number of pixels down from the origin.
For example, the point (100,100) is 100 pixels over and 100 pixels down from the
upper-left corner of the screen. Suppose that a Frame is instantiated and given the bounds
(100,100, 300, 400):
Frame f = new Frame();
f.setBounds(100, 100, 300, 400);
The upper-left corner of the Frame is the point (100,100) relative to the computer
screen. The width of this Frame is 300 and the height is 400, so the lower-right corner of
the Frame is the point (400, 500) of the computer screen.
There is another coordinate system of GUI components referred to as the relative coor-
dinate system . The relative coordinate system is based on the upper-left corner of the con-
tainer that the component is residing in. The upper-left corner of a container is an origin
(0,0), and components are placed in a container relative to the container's origin, not the
screen's origin.
For example, the following statements instantiate a Button, assign it bounds (20, 200,
60, 40). The Button is then added to the Frame object instantiated earlier:
Button ok = new Button(“OK”);
ok.setBounds(20, 200, 60, 40);
f.add(ok); //Add the Button to a Frame
The upper-left corner of the OK button appears 20 pixels over and 200 pixels down
from the upper-left corner of the Frame. The size of the Button is 60 pixels wide and 40
pixels high.
Assuming that Frame f has not been moved, this puts the Button 120 pixels over and
300 pixels down from the upper-left corner of the screen. This point changes if the Frame
is moved. However, the relative location of the Button within the Frame does not move,
even if the Frame moves. This is the desired result of GUI containers and components.
When we move a window, we expect all the components within the window to move along
with it. Therefore, we rarely concern ourselves with the actual screen coordinates of a com-
ponent. The component's relative coordinates are what are important to a programmer
laying out components in a container.
After you have instantiated a Frame, given it a size, and laid out the compo-
nents within it, you display the Frame on the screen by invoking the setVisible()
method inherited from the Component class. The signature of setVisible() is:
public void setVisible(boolean show)
Search WWH ::




Custom Search