Built-in colors. The simplest way to specify colors using standard draw is via a list of predefined colors. You can set the foreground color to blue with:
or clear the background to light gray with:StdDraw.setPenColor(StdDraw.BLUE);
The default foreground color is black and the default background color is white. Here is the complete list of predefined colors.StdDraw.clear(StdDraw.LIGHT_GRAY);
StdDraw.BLACK StdDraw.BLUE StdDraw.CYAN StdDraw.DARK_GRAY StdDraw.GRAY StdDraw.GREEN StdDraw.LIGHT_GRAY StdDraw.MAGENTA StdDraw.ORANGE StdDraw.PINK StdDraw.RED StdDraw.WHITE StdDraw.YELLOW
User-defined colors. The Java class Color allows you to construct your own colors using RGB or HSB formats. For complete details check out the Java Color API. Unless you have extreme needs, the following examples will probably suffice: (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:
import java.awt.Color
Note that if all three arguments 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.setPenColor(new Color(255, 0, 0)); // red StdDraw.setPenColor(new Color( 0, 255, 0)); // green StdDraw.setPenColor(new Color( 0, 0, 255)); // blue StdDraw.setPenColor(new Color(255, 255, 0)); // yellow StdDraw.setPenColor(new Color(255, 255, 255)); // white StdDraw.setPenColor(new Color( 0, 0, 0)); // black StdDraw.setPenColor(new Color(100, 100, 100)); // gray
StdDraw.setPenColor(Color.decode("#00ffff")); // cyan
for (int i = 0; i < 256; i++) {
StdDraw.setPenColor(Color.getHSBColor(i / 256.0f, 1.0f, 1.0f));
// plot something
}
The three input parameters to Color.getHSBColor are of
real numbers of type float - this is why you need to
use 1.0f instead of 1.0.
It's also can be fun to generate random colors. The following code
fragment generates a random color from the rainbow.
StdDraw.setPenColor(Color.getHSBColor((float) Math.random(), .8f, .8f));