Java: Color

Description

The java.awt.Color class is used to create new colors, and predefines a few color constants (see below). Java allows the creation of up to 24 million different colors.

Because our eyes have three kinds of neurons that respond primarily to red, green, and blue, it's possible for computer monitors (and TVs) to create all colors using the RGB system. The RGB system Java uses combines red, green, and blue in amounts represented by a number from 0 to 255. For example, red is (255, 0, 0) -- 255 units of red, no green, and no blue. White is (255, 255, 255) and black is (0,0,0).

Color Constants

Java originally defined a few color constant names in lowercase, which violated the naming rule of using uppercase for constants. These are best to use since they are available in all versions of Java: Color.black, Color.darkGray, Color.gray, Color.lightGray, Color.white, Color.magenta, Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.cyan, Color.blue Java 1.4 added the proper uppercase names for constants: Color.BLACK, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY, Color.WHITE, Color.MAGENTA, Color.RED, Color.PINK, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE

Constructor

Color c = new Color(int red, int green, int blue)
This creates a new color object that is a combination of red, green, and blue. The values of each color must be in the range 0-255.

Don't do anything to a Color

A Color object is created only to be passed as a parameter. You will never call any Color methods.

Example

Color c = new Color(255, 255, 240);
this.setBackground(c);

Advanced

Additional constructors use single packed ints or floating point values. In addition, there is support for the HSB (Hue, Saturation, Brightness) color model and transparency. There is a Color Chooser in Java 2 that lets the user choose a color.

See Also

Example - ColorDisplay example with sliders to adjust each of the RGB colors.