Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

330 HOUR 23:Creating Java2D Graphics


The Graphics2Dobject has methods used to draw text with a command
such as the following:
comp2D.drawString(“Draw, pardner!”, 15, 40);

This draws the text “Draw, pardner!” at the coordinates (15,40). Drawing
methods use the same (x,y) coordinate system as text. The (0,0) coordinate
is at the upper-left corner of the container, x values increase to the right,
and y values increase as you go down. You can determine the maximum
(x,y) value you can use in an applet with the following statements:
int maxXValue = getSize().width;
int maxYValue = getSize().height;

With the exception of lines, shapes you draw can be filled or unfilled. A
filled shape is drawn with the current color completely filling the space
taken up by the shape. Unfilled shapes draw a border with the current
color.

Drawing Lines
A 2D drawing of an object is created and represents the shape that is being
drawn.
The objects that define shapes belong to the java.awt.geompackage of
classes.
The Line2D.Floatclass creates a line connecting a beginning (x,y) point
and an ending (x,y) point. The following statement creates a line from the
point (40,200) to the point (70,130):
Line2D.Float line = new Line2D.Float(40F, 200F, 70F, 130F);

The arguments are followed by the letter Fto indicate they are floating-
point values. If this was omitted, Java would treat them as integers.
All shapes except for lines are drawn by calling a method of the
Graphics2Dclass—draw()for outlines and fill()for filled shapes.
The following statementdraws the lineobject created in the previous
example:
comp2D.draw(line);

NOTE
Line2D.Floathas a period in
the middle of its class name,
which differs from most classes
you’ve worked with before.
That’s because Floatis an
inner class of the Line2Dclass,
a subject covered in Hour 11,
“Describing What Your Object Is
Like.”

Free download pdf