Java Reference
In-Depth Information
Figure 3G.8
Output of DrawLoop1
black. But once we make a call on
setColor
changing the color to white, every sub-
sequent drawing and filling command is done in white, including the second, third,
and fourth rectangles.
So, we need to include calls to set the color to black to draw the rectangles and to
set the color to white to draw the filled ovals. While we're at it, it's a good idea to
switch the order of these tasks. The rectangles and ovals overlap slightly, and we
would rather have the rectangle drawn over the oval than the other way around. The
following program produces the correct output:
1 // Draws boxed ovals using a for loop.
2
3
import
java.awt.*;
4
5
public class
DrawLoop2 {
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.setColor(Color.WHITE);
13
g.fillOval(i * 50, i * 25, 50, 25);
14
g.setColor(Color.BLACK);
15
g.drawRect(i * 50, i * 25, 50, 25);
16
}
17
}
18 }
It's also possible to create custom
Color
objects of your own, rather than using
the constant colors provided in the
Color
class. Computer monitors use red,
green, and blue (RGB) as their primary colors, so when you construct a
Color
Search WWH ::
Custom Search