Java AWT Create Color Object


With colors and fonts, readability increases as important noteworthy topics can be colored. All the latest operating systems support colors and fonts and allow customizing also. To support colors and fonts, the java.awt package includes Color class and Font class.

Standard Color Models

Color can be specified in two formats – RGB and HSB.

1. RGB Model

RGB model comes with the combination of primary colors red, green and blue. Different proportions of these three components give different shades. The range of values of these three, passed to Color constructor, should be within 0 to 255. Going out side this range raises IllegalArgumentException. With different combination of these colors, 16 million shaded can be created.

Syntax:

Color clr1 = new Color(int red, int green, int blue);

Examples:

         Color clr1 = new Color(200, 50, 150);      // some color shade
         Color clr2 = new Color(200, 0, 0);        // pure red color
         Color clr3 = new Color(255, 255, 255);    // white
         Color clr4 = new Color(0, 0, 0);          // black

2. HSB Model

HSB model comes with the combination of Hue, Saturation and Brightness. The range of values of these three components, passed to Color constructor, should be within 0.0f to 1.0f. That, is HSB model takes floating-point values (RGB takes integer values). Going out side this range raises IllegalArgumentException.

Syntax:

Color clr1 = new Color(float red, float green, float blue);

Examples:

Color clr1 = new Color(0.85f, 0.2f, 0.36f); // some color shade
Color clr2 = new Color(1.0f, 0, 0); // pure red color
Color clr3 = new Color(1.0f, 1.0f, 1.0f); // white
Color clr4 = new Color(0.0f, 0.0f, 0.0f); // black

Java designers identified 13 colors as most frequently used by programmers. These colors can be used straightaway by the programmer without creating objects. These 13 colors are defined as static constants in Color class.

Following are the colors.

red green blue
black white
gray lightGray darkGray
pink yellow magenta cyan orange

Other than these 13, if the programmer desires some other color, he must create a Color object and use.

Following is the class signature

public class Color extends Object implements Paint, Serializable

Leave a Comment

Your email address will not be published.