Java Reference
In-Depth Information
The coordinate system assigns the upper-left corner of a panel the position (0, 0).
As you move to the right of this position, the
x
value increases. As you move down
from this position, the
y
value increases. For example, suppose that you construct a
DrawingPanel
object with a width of 200 pixels and a height of 100 pixels. The
upper-left corner will have the coordinates (0, 0), and the lower-right corner will have
the coordinates (199, 99).
x
(0, 0)
(199, 99)
y
Figure 3G.1
The x/y Coordinate Space
This is likely to be confusing at first, because you're probably used to coordinate
systems where
y
values decrease as you move down. However, you'll soon get the
hang of it.
So, how do you actually draw something? To draw shapes and lines, you don't talk
directly to the
DrawingPanel
, but rather to a related object of type
Graphics
. Think
of the
DrawingPanel
as a canvas and the
Graphics
object as the paintbrush. The
DrawingPanel
class has a method called
getGraphics
that returns its
Graphics
object:
Graphics g = <panel>.getGraphics();
One of the simplest drawing commands is
drawLine
, which takes four integer
arguments.
For example, the method:
g.drawLine(<x1>, <y1>, <x2>, <y2>);
draws a line from the point (
x
1,
y
1) to the point (
x
2,
y
2). The
drawLine
method is
just one of many commands a
Graphics
object understands; see Table 3G.2 for oth-
ers. The
Graphics
object has many more methods in addition to the ones discussed
here. You can read about them in the Java API documentation.
Here is a sample program that puts these pieces together:
1 // Draws a line onto a DrawingPanel.
2
3
import
java.awt.*;
// for graphics
4
Search WWH ::
Custom Search