Java Reference
In-Depth Information
The practical reality of color management is that the color you designate with sRGB will
not be available on all output devices. If you need more precise control of the color, you
can use
ColorSpace
and other classes in the
java.awt.color
package.
For most uses, the built-in use of sRGB to define colors should be sufficient.
Using
Color
Objects
Colors are represented by
Color
objects, which can be created with a constructor or by
using one of the standard colors available from the
Color
class.
You can call the
Color
constructor to create a color in two ways:
Use three integers that represent the sRGB value of the desired color.
n
Use three floating-point numbers that represent the desired sRGB value.
n
You can specify a color's sRGB value using either three
int
or three
float
values. The
following statements show examples of each:
Color c1 = new Color(0.807F, 1F, 0F);
Color c2 = new Color(255, 204, 102);
The
c1
object describes a neon green color, and
c2
is butterscotch.
It's easy to confuse floating-point literals such as 0F and 1F with
hexadecimal numbers, which were discussed on Day 2, “The ABCs
of Programming.” Colors are often expressed in hexadecimal, such
as when a background color is set for a web page using the HTML
BODY
tag. The Java classes and methods you work with don't take
hexadecimal arguments, so when you see a literal such as 1F or
0F, you're dealing with floating-point numbers.
NOTE
Testing and Setting the Current Colors
The current color for drawing is designated by using the
setColor()
method of the
Graphics2D
class. This method must be called on the
Graphics2D
object that represents
the area to which something is being drawn.
Several of the most common colors are available as class variables in the
Color
class.
These colors use the following
Color
variables (with sRGB values indicated within
parentheses):