Java Reference
In-Depth Information
Method
Description
public int
getGreen()
Returns a value between 0 and 255 representing the green content.
public int
getBlue()
Returns a value between 0 and 255 representing the blue content.
Graphics
methods for manipulating
Color
s
public
Color getColor()
Returns
Color
object representing current color for the graphics context.
public
void setColor(Color c)
Sets the current color for drawing with the graphics context.
Fig. 13.4
|
Color
methods and color-related
Graphics
methods. (Part 2 of 2.)
Every color is created from a red, a green and a blue value. Together these are called
RGB values
. All three RGB components can be integers in the range from 0 to 255, or all
three can be floating-point values in the range 0.0 to 1.0. The first RGB component spec-
ifies the amount of red, the second the amount of green and the third the amount of blue.
The larger the value, the greater the amount of that particular color. Java enables you to
choose from 256
256 (approximately 16.7 million) colors. Not all computers are
capable of displaying all these colors. The screen will display the closest color it can.
Two of class
Color
'
s
constructors are shown in Fig. 13.4—one that takes three
int
arguments and one that takes three
float
arguments, with each argument specifying the
amount of red, green and blue. The
int
values must be in the range 0-255 and the
float
values in the range 0.0-1.0. The new
Color
object will have the specified amounts of red,
green and blue.
Color
methods
getRed
,
getGreen
and
getBlue
return integer values from
0 to 255 representing the amounts of red, green and blue, respectively.
Graphics
method
getColor
returns a
Color
object representing the
Graphics
object's current drawing color.
Graphics
method
setColor
sets the current drawing color.
×
256
×
Drawing in Different Colors
Figures 13.5-13.6 demonstrate several methods from Fig. 13.4 by drawing
filled rectangles
and
String
s in several different colors. When the application begins execution, class
Col-
orJPanel
's
paintComponent
method (lines 10-37 of Fig. 13.5) is called to paint the win-
dow. Line 17 uses
Graphics
method
setColor
to set the drawing color. Method
setColor
receives a
Color
object. The expression
new Color(255, 0, 0)
creates a new
Color
object
that represents red (red value
255
, and
0
for the green and blue values). Line 18 uses
Graphics
method
fillRect
to draw a
filled rectangle
in the current color. Method
fill-
Rect
draws a rectangle based on its four arguments. The first two integer values represent
the upper-left
x
-coordinate and upper-left
y
-coordinate, where the
Graphics
object begins
drawing the rectangle. The third and fourth arguments are nonnegative integers that
represent the width and the height of the rectangle in pixels, respectively. A rectangle
drawn using method
fillRect
is filled by the current color of the
Graphics
object.