Java Create Color
Summary: By the end of this tutorial "Java Create Color", you can create a Color object with different color components. Explained in simple terms. Go further
The best way to present the graphics is in good attractive colors and fonts. Colors and fonts give readability and emphasis to the drawings that can catch user's attention immediately (including thicker lines). Nature is full of colored objects like sky, flowers and earth etc. Color is an eye-catching ingredient that improves the text visibility with useful and important information. java.awt package, to support various colors and fonts, comes with two classes – Color and Font. With Color class, we can create 16 million colors. Following styles can be adapted to do with colors.
Various colors can be created by passing different RGB (Red, Green, Blue) values to Color constructor.
Color clr1 = new Color(int red, int green, int blue); // RGB notation
Here the parameter values must be 0 to 255 only. Any outside range raises IllegalArgumentException.
Color clr1 = new Color(100, 50, 200); // some color
Color clr2 = new Color(128, 128, 128); // gray color
Color clr3 = new Color(255, 0, 0); // red color
There exists another style of giving color values known as HSB (Hue, Saturation, Brightness) notation. Here the parameters are floating-point values ranging from 0.0f to 1.0f.
Color clr1 = new Color(float red, float green, float blue);
Color clr1 = new Color(0.2f, 0.52f, 0.9f); // some color
Color clr2 = new Color(0.5f, 0.5f, 0.5f); // gray color
Color clr3 = new Color(1.0f, 0.0f, 0.0f); // red color
Java identifies 13 colors as most frequently used by the programmers. These colors can be used straightaway without creating objects. They are defined as static constants in Color class. Following are the colors.
Other than these, it is necessary to create Color object and use. The methods like setBackground(), setForeground() and setColor() take color object as parameter.