Java Reference
In-Depth Information
Figure 5.5
Now that we know how to change the color for pens and canvases, we can do some more exercises.
Exercise 5.55 Create a canvas. Using the canvas's methods interactively, draw a red circle
near the center of the canvas. Now draw a yellow rectangle.
Exercise 5.56 How do you clear the whole canvas?
As you have seen, we can either draw directly on to the canvas or we can use a pen object to
draw. The pen provides us with an abstraction that holds a current position, rotation, and color,
and this makes producing some kinds of drawings easier. Let us experiment with this a bit
more, this time by writing code in a class instead of using interactive calls.
Exercise 5.57 In class DrawDemo , create a new method named drawTriangle . This
method should create a pen (as in the drawSquare method) and then draw a green triangle.
Exercise 5.58 Write a method drawPentagon that draws a pentagon.
Exercise 5.59 Write a method drawPolygon(int n) that draws a regular polygon with
n sides (thus, n=3 draws a triangle, n=4 draws a square, etc.).
Exercise 5.60 Write a method called spiral that draws a spiral (see Figure 5.6).
Figure 5.6
A spiral drawn on the
canvas
Search WWH ::




Custom Search