Java Reference
In-Depth Information
Table 3G.3
Color Constants
Color.BLACK
Color.GREEN
Color.RED
Color.BLUE
Color.LIGHT_GRAY
Color.WHITE
Color.CYAN
Color.MAGENTA
Color.YELLOW
Color.DARK_GRAY
Color.ORANGE
Color.GRAY
Color.PINK
There are a number of predefined colors that you can refer to directly. They are
defined as class constants in the
Color
class (a lot like the constants we used in Chapter
2). The names of these constants are all in uppercase and are self-explanatory. To refer to
one of these colors, you have to precede it with the class name and a dot, as in
Color.GREEN
or
Color.BLUE
. The predefined
Color
constants are listed in Table 3G.3.
As mentioned earlier, the
DrawingPanel
object has a method that can be used to
change the background color that covers the entire panel:
<panel>.setBackground(<color>);
Likewise, the
Graphics
object has a method that can be used to change the cur-
rent color that draws or fills shapes and lines:
g.setColor(<color>);
Calling
setColor
is like dipping your paintbrush in a different color of paint.
From that point on, all drawing and filling will be done in the specified color. For
example, here is another version of the previous program that uses a cyan (light blue)
background color and fills in the oval and square with white instead of black:
1 // Draws and fills shapes in different colors.
2
3
import
java.awt.*;
4
5
public class
DrawColoredShapes {
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
g.drawRect(150, 10, 40, 20);
12
g.drawOval(50, 25, 20, 20);
13
g.setColor(Color.WHITE);
14
g.fillOval(150, 50, 40, 20);
15
g.fillRect(25, 50, 20, 20);
16
}
17 }
Search WWH ::
Custom Search