Java Reference
In-Depth Information
Can you spot the pattern between the two for loops used to draw the stairs of the
pyramids? The x - and y -coordinates differ only in the addition of the offset from
(0, 0) in the second loop. The stairs' widths and heights differ only in that one pyra-
mid's stairs are 20 pixels tall and the other pyramid's stairs are 10 pixels tall (the
result of dividing the overall size of 100 by the number of stairs).
Using the preceding information, let's turn the code for drawing a pyramid into
a method that we can call three times to avoid redundancy. The parameters will be
the ( x , y ) coordinates of the top-left corner of the pyramid's bounding box and the
number of stairs in the pyramid. We'll also need to pass Graphics g as a parame-
ter so that we can draw onto the DrawingPanel . We'll modify the for loop to
compute the stair height first, then use the height to compute the stair width, and
finally use the width and height to help compute the ( x , y ) coordinates of the stair.
Here's the code:
public static void drawPyramid(Graphics g, int x,
int y, int stairs) {
// draws the border rectangle
g.drawRect(x, y, 100, 100);
// draws the stairs of the pyramid
for (int i = 0; i < stairs; i++) {
int stairHeight = 100 / stairs;
int stairWidth = stairHeight * (i + 1);
int stairX = x + (100 - stairWidth) / 2;
int stairY = y + stairHeight * i;
g.drawRect(stairX, stairY, stairWidth, stairHeight);
}
}
The preceding code is now generalized to draw a pyramid at any location with any
number of stairs. But one final ingredient is missing: the ability to give a different
color to each pyramid.
Complete Structured Solution
The preceding code is correct except that it doesn't allow us to draw the pyramids in
the proper colors. Let's add an additional parameter, a Color , to our method and use
it to fill the pyramid stairs as needed. We'll pass Color.WHITE as this parameter's
value for the first white pyramid; it'll fill the stairs with white, even though this isn't
necessary.
The way to draw a filled shape with an outline of a different color is to first fill the
shape, then use the outline color to draw the same shape. For example, to get red rec-
tangles with black outlines, first we'll use fillRect with red, then we'll use
drawRect with black with the same parameters.
 
Search WWH ::




Custom Search