Life would
be dull if we have to limit ourselves to the predefined colors such as Color.green and Color.gray. Luckily Java allows us to create arbitrary
colors in such a way that makes it possible to manipulate and use them similarly
to variables. Combined with loops,
this opens up the possibilities to create many exciting types of
programs. To work with
colors, we first need to understand one of the color model
that Java adopts. The simplest is the
RGB model, which defines all colors as a combination of three primary colors:
Red, Green and Blue.
Each of the primary colors has 256 intensities expressed by the
integer values 0 to 255. A zero intensity represents the lack of a color, and 255
is the color at full intensity. With
such a system, a color is defined by the intensities of the 3 primary
colors. The color black is (0,0,0), whereas white is the result of the colors being at
maximum intensity, (255, 255, 255). If
the intensities of the 3 primary colors are the same, the color produced is
monochromatic – it corresponds to the different shades of gray
(grayscale). The RGB model allows 256
shades of gray: (0,0,0), (1,1,1), (2,2,2), …, (255, 255,255). Since each of the three primary colors can
take on 256 intensities, the total number of colors that we can represent is
2563, which is approximately 16.7 million
colors! To define a
color in Java, we have to create an object of the class Color (remember that you’ll need to import java.awt.Color). The following
statement creates a Color object with RGB intensities (10, 10, 250), with an object
reference called myColor: Color myColor = new Color(10, 10, 250); Assuming we
have a board object, we can color the top left hand corner of the board with
the color just defined using the statement: b.fillCell(0, 0, myColor); Since the
intensity of blue is much higher than that of other colors, we would expect
the color produced to be bluish (try it out).
|