The Java class Color allows you to use a myriad of built-in colors.
Or, you can create your own from RGB or HSB formats.
(We'll introduce classes in Section 3.1.)
To access the Color class, you need to include the following statement
at the beginning of your Java program:
You can now set the foreground color to blue using our standard graphics library with:import java.awt.Color
or clear the background withStdDraw.setColor(Color.blue);
The default foreground color is black and the default background color is white.StdDraw.clear(Color.lightGray);
Built-in colors. The following colors are built-in:
Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow
User-defined colors. There are a number of ways to construct your own colors. For complete details check out the Java Color API. Unless you have extreme needs, the following examples will probably suffice:
Note that if all three parameters are the same, you get a shade of gray. Web pages typically specify the colors in RGB format, but as a 24-bit hexadecimal integer. You can achieve the same effect in Java.StdDraw.setColorRGB(255, 0, 0); // red StdDraw.setColorRGB( 0, 255, 0); // green StdDraw.setColorRGB( 0, 0, 255); // blue StdDraw.setColorRGB(255, 255, 0); // yellow StdDraw.setColorRGB(255, 255, 255); // white StdDraw.setColorRGB( 0, 0, 0); // black StdDraw.setColorRGB(100, 100, 100); // gray
StdDraw.setColor(Color.decode("#00ffff")); // cyan
for (int i = 0; i <256; i++) { stddraw.setcolorhsb(i, 255, 255); // plot something }
It's also can be fun to generate random colors. The following code
fragment generates a random color from the rainbow.
int r = (int) (Math.random() * 256); StdDraw.setColorHSB(r, 255, 255);