Java Reference
In-Depth Information
Figure 3G.7
Desired Output of DrawLoop1
upper-left corners are different. The first rectangle's upper-left corner is at (0, 0), the
second is at (50, 25), the third is at (100, 50), and the fourth is at (150, 75). We need
to write code to generate these different coordinates.
This is a great place to use a for loop. Using the techniques introduced in Chapter 2, we
can make a table and develop a formula for the coordinates. In this case it is easier to
have the loop start with 0 rather than 1, which will often be the case with drawing pro-
grams. Here is a program that makes a good first stab at generating the desired output:
1 // Draws boxed ovals using a for loop (flawed version).
2
3 import java.awt.*;
4
5 public class DrawLoop1 {
6
public static void main(String[] args) {
7
DrawingPanel panel = new DrawingPanel(200, 100);
8
panel.setBackground(Color.CYAN);
9
10
Graphics g = panel.getGraphics();
11
for ( int i = 0; i < 4; i++) {
12
g.drawRect(i * 50, i * 25, 50, 25);
13
g.setColor(Color.WHITE);
14
g.fillOval(i * 50, i * 25, 50, 25);
15
}
16
}
17 }
This program produces the output shown in Figure 3G.8.
The coordinates and sizes are right, but not the colors. Instead of getting four
black rectangles with white ovals inside, we're getting one black rectangle and three
white rectangles. That's because we only have one call on setColor inside the loop.
Initially the color will be set to black, which is why the first rectangle comes out
Search WWH ::




Custom Search