Working with Colors

Every color under the rainbow can be expressed as some combination of the primary colors red, green, and blue. To get different colors, one simply varies the intensity of each primary color combined. For example,

purple =  100% red  +  0%   green  +  100%  blue
orange =  100% red  +  68%  green  +  0%    blue
gray   =  50%  red  +  50%  green  +  50%   blue
white  =  100% red  +  100% green  +  100%  blue
black  =  0%   red  +  0%   green  +  0%    blue

When we create a new instance of the java.awt.Color class, we can specify the intensity of each primary color with an integer from 0 to 255, with 0 corresponding to 0% and 255 corresponding to 100%. With this in mind, and presuming that random is an instance of the java.util.Random class, the following code will create a random color:

int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
Color randomColor = new Color(red,green,blue);

The java.awt.Color class offers a quick way to specify certain colors. For example, in the following code snippet, both color1 and color2 end up being green:

Color color1 = new Color(0,255,0); 
Color color2 = Color.GREEN;

To find out which colors with which you can use this shortcut, consult the Java API.

When working with the ACM libraries, and presuming rect is an instance of the acm.graphics.GRect class and someColor is an instance of the java.awt.Color class, note that the following code will fill the rectangle rect with the color someFillColor.

rect.setFilled(true);
rect.setFillColor(someColor);

If only the edge of the rectangle was to be colored, the following would have sufficed:

rect.setColor(someColor);