prev | TOC | next

Specifying Colors in Java

file: ColorExample.java (help)


Color is used quite often in writing your turtles.  You can set the color of the pen or the background of the display.  There are several ways to indicate a color in Java:

1. Use the Color classes static color variables:

Color.black

Color.lightGray

Color.blue

Color.magenta

Color.cyan

Color.orange

Color.darkGray

Color.pink

Color.gray

Color.red

Color.green

Color.white

Color.yellow


For example, setPenColor(Color.green);

Since the variables black, blue, green, etc. are static variables of the Color class, you must be sure to include the "Color" class name and a period "." before typing the variable name. 


2. Mix your own colors using the RGB (Red, Green, Blue) color model when creating a new Color object:

        new Color(red, green, blue)

  • Where red is a integer between 0 and 255 to indicate the amount of red
  • Where green is a integer between 0 and 255 to indicate the amount of green
  • Where blue is a integer between 0 and 255 to indicate the amount of blue

The "new" directive specifies that you want to create a new instance of a Color object.  When creating the new object, you specify how much red, green and blue you want in the new color.

For example, setPenColor(new Color(255, 0, 255));

[This will set the pen color to purple (a mix of red and blue.]


3. Mix your own colors using the HSB color model when creating a new Color object:

        Color.getHSBColor(hue, saturation, brightness)

  • The hue parameter is a decimal number between 0.0 and 1.0 which indicates the hue of the color. You'll have to experiment with the hue number to find out what color it represents.
  • The saturation is a decimal number between 0.0 and 1.0 which indicates how deep the color should be. Supplying a "1" will make the color as deep as possible, and to the other extreme, supplying a "0," will take all the color out of the mixture and make it a shade of gray.
  • The brightness is also a decimal number between 0.0 and 1.0 which obviously indicates how bright the color should be. A 1 will make the color as light as possible and a 0 will make it very dark.

The getHSBColor is a static method in the Color class.  It creates a new Color object with the specified hue, saturation and brightness and returns it as a result.

For example, setPenColor(Color.getHSBColor(0.56f, 1.0f, 0.8f));


The Color class has a number of other ways to create or manipulate color.  To learn more about them choose the Show Java API menu command and locate the Color class in the java.awt package.

Exercises

Create a turtle as in previous exercises.  Set the pen color or background color to different values using setPenColor() and setDisplayColor().  Practice all three ways mentioned above of getting a new Color object.  Experiment and have fun.