Java Reference
In-Depth Information
This program produces the output shown in Figure 3G.14.
Figure 3G.14
Output of DrawDiamonds
It's possible to draw patterned figures in loops and to have one drawing method
call another. For example, if we want to draw five diamonds, starting at (12, 15) and
spaced 60 pixels apart, we just need a for loop that repeats five times and shifts the
x -coordinate by 60 each time. Here's an example loop:
for (int i = 0; i < 5; i++) {
drawDiamond(g, 12 + 60 * i, 15);
}
If we created another method to draw the line of five diamonds, we could call it
from main to draw many lines of diamonds. Here's a modified version of the
DrawDiamonds program with two graphical methods:
1 // This program draws several diamond figures of size 50x50.
2
3 import java.awt.*;
4
5 public class DrawDiamonds2 {
6
public static void main(String[] args) {
7
DrawingPanel panel = new DrawingPanel(360, 160);
8
Graphics g = panel.getGraphics();
9
10
drawManyDiamonds(g, 12, 15);
11
g.setColor(Color.RED);
12
drawManyDiamonds(g, 55, 100);
13
}
14
15
// draws five diamonds in a horizontal line
Search WWH ::




Custom Search