Java Reference
In-Depth Information
Here's the new version of the drawPyramid method that uses the fill color as a
parameter:
public static void drawPyramid(Graphics g, Color c,
int x, int y, int stairs) {
g.drawRect(x, y, 100, 100);
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.setColor(c);
g.fillRect(stairX, stairY, stairWidth, stairHeight);
g.setColor(Color.BLACK);
g.drawRect(stairX, stairY, stairWidth, stairHeight);
}
}
Using this method, we can now draw all three pyramids easily by calling
drawPyramid three times with the appropriate parameters:
drawPyramid(g, Color.WHITE, 0, 0, 10);
drawPyramid(g, Color.RED, 80, 140, 5);
drawPyramid(g, Color.BLUE, 220, 50, 20);
One last improvement we can make to our Pyramids program is to turn the over-
all pyramid size of 100 into a constant, so there aren't so many 100s lying around in
the code. Here is the complete program:
1 // This program draws three colored pyramid figures.
2
3 import java.awt.*;
4
5 public class Pyramids {
6
public static final int SIZE = 100;
7
8
public static void main(String[] args) {
9
DrawingPanel panel = new DrawingPanel(350, 250);
10
Graphics g = panel.getGraphics();
11
12
drawPyramid(g, Color.WHITE, 0, 0, 10);
13
drawPyramid(g, Color.RED, 80, 140, 5);
14
drawPyramid(g, Color.BLUE, 220, 50, 20);
15
}
16
17
// draws one pyramid figure with the given
Search WWH ::




Custom Search