Java Reference
In-Depth Information
Specifying a Drawing Color
When drawing figures with methods such as drawLine inside of the definition of the
paint method, you can think of your drawing as being done with a pen that can
change colors. The method setColor will change the color of the pen.
For example, consider the happy face that is drawn by the GUI in Display 18.13. If
you change the definition of the paint method to the version shown in Display 18.18,
the eyes will be blue and the mouth will be red. (The file HappyFaceColor.java on the
accompanying CD contains a version of the changed program. It consists of the pro-
gram in Display 18.13 with the definition of the paint method replaced by the one in
Display 18.18 and with the class name changed from HappyFace to HappyFaceColor .)
setColor
extra
code on
CD
The setColor Method
When you are doing drawings with an object of the class Graphics , you can set the color of
the drawing with an invocation of setColor . The color specified can later be changed with
another invocation of setColor , so a single drawing can have multiple colors.
SYNTAX
Graphics_Object .setColor( Color_Object );
EXAMPLE
g.setColor(Color.BLUE);
Display 18.18 Adding Color
1
public void paint(Graphics g)
2
{
3
super .paint(g);
4
//Default is equivalent to: g.setColor(Color.black);
5
g.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);
6
//Draw Eyes:
7
g.setColor(Color.BLUE);
g.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT);
8
g.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT);
9
10
//Draw Mouth:
11
g.setColor(Color.RED);
g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT,
12
13
MOUTH_START_ANGLE, MOUTH_ARC_SWEEP);
14
}
If you replace the method paint in Display 18.13 with this version of
paint , then the happy face will have blue eyes and red lips.
 
Search WWH ::




Custom Search