Java Reference
In-Depth Information
This program produces the output shown in Figure 3G.6. (The figures shown in
this textbook may not match the colors you would see on your screen.)
Figure 3G.6
Output of DrawColoredShapes
Notice that you tell the panel to set the background color, while you tell the
Graphics object to set the foreground color. The reasoning is that the background
color is a property of the entire window, while the foreground color affects only the
particular shapes that you draw.
Notice also that the order of the calls has been rearranged. The two drawing com-
mands appear first, then the call on setColor that changes the color to white, then
the two filling commands. This ensures that the drawing is done in black and the fill-
ing is done in white. The order of operations is very important in these drawing pro-
grams, so you'll have to keep track of what your current color is each time you give a
new command to draw or fill something.
Common Programming Error
Misunderstanding Draw vs. Fill
Some new programmers think that a shape must be drawn (such as with
drawRect ) before it can be filled in (such as with fillRect ). This is not the
case. In fact, when you are trying to draw an outlined shape, this is exactly the
wrong thing to do. Suppose you want to draw a 60x30 green rectangle with a
black border at (20, 50). You might write the following code:
g.setColor(Color.BLACK); // incorrect code
g.drawRect(20, 50, 60, 30);
g.setColor(Color.GREEN);
g.fillRect(20, 50, 60, 30);
Continued on next page
 
Search WWH ::




Custom Search