Color is not a property of a particular rectangle, string or other
thing you may draw. Rather color is a part of the Graphics
object that does the drawing. To change colors you
change the color of your Graphics
object. Then
everything you draw from that point forward will be in the new
color, at least until you change it again.
When an applet starts running the color is set to black by
default. You can change this to red by calling g.setColor(Color.red)
. You can change it back to black by
calling g.setColor(Color.black)
. The following code
fragment shows how you'd draw a pink String followed by a green
one:
g.setColor(Color.pink);
g.drawString("This String is pink!", 50, 25);
g.setColor(Color.green);
g.drawString("This String is green!", 50, 50);
Remember everything you draw after the last line will be drawn in
green. Therefore before you start messing with the color of the pen
its a good idea to make sure you can go back to the color you
started with. For this purpose Java provides the getColor()
method. You use it like follows:
Color oldColor = g.getColor();
g.setColor(Color.pink);
g.drawString("This String is pink!", 50, 25);
g.setColor(Color.green);
g.drawString("This String is green!", 50, 50);
g.setColor(oldColor);