Java Reference
In-Depth Information
p1.setLocation(p1.x, p1.y - height1);
p2.setLocation(p2.x, p2.y - height2);
g2D.draw(new Line2D.Float(p1, p2));
g2D.drawString("Lines and rectangles", 60, 250); // Draw some text
}
Directory "Sketcher 2 drawing lines and rectangles"
If you type this code in correctly and recompile the SketcherView class, the Sketcher window looks like
the one shown in Figure 19-9 .
FIGURE 19-9
How It Works
After casting the graphics context object that is passed to the paint() method to type Graphics2D , you
set the drawing color to red. All subsequent drawing that you do is in red until you change the color with
another call to setPaint() . You define a Point2D.Float object to represent the position of the first
rectangle, and you define variables to hold the width and height of the rectangle. You use these to create
the rectangle by passing them as arguments to the constructor that you saw earlier in this chapter and
display the rectangle by passing the rect object to the draw() method for the graphics context, g2D . The
second rectangle is defined by essentially the same process, except that this time you create the Rect-
angle2D.Float object in the argument expression for the draw() method.
Note that you have to cast the values returned by the getX() and getY() members of the Point2D object,
as they are returned as type double . It is generally more convenient to reference the x and y fields dir-
ectly as you do in the rest of the code.
You change the drawing color to blue so that you can see quite clearly the lines you are drawing. You
use the setLocation() method for the point objects to move the point on each rectangle to successive
corners and draw a line at each position. The caption also appears in blue because that is the color in
effect when you call the drawString() method to output the text string.
 
 
Search WWH ::




Custom Search