Java Reference
In-Depth Information
10
// create frame for ColorJPanel
11
JFrame frame = new JFrame( "Using colors" );
12
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13
14
ColorJPanel colorJPanel = new ColorJPanel();
15
frame.add(colorJPanel);
16
frame.setSize( 400 , 180 );
17
frame.setVisible( true );
18
}
19
} // end class ShowColors
Fig. 13.6 | Demonstrating Color s. (Part 2 of 2.)
Line 19 uses Graphics method drawString to draw a String in the current color.
The expression g.getColor() retrieves the current color from the Graphics object. We
then concatenate the Color with string "Current RGB: " , resulting in an implicit call to
class Color 's toString method. The String representation of a Color contains the class
name and package ( java.awt.Color ) and the red, green and blue values.
Look-and-Feel Observation 13.1
People perceive colors differently. Choose your colors carefully to ensure that your applica-
tion is readable, both for people who can perceive color and for those who are color blind.
Try to avoid using many different colors in close proximity.
Lines 22-24 and 27-29 perform the same tasks again. Line 22 uses the Color con-
structor with three float arguments to create a dark green color ( 0.50f for red, 0.75f for
green and 0.0f for blue). Note the syntax of the values. The letter f appended to a
floating-point literal indicates that the literal should be treated as type float . Recall that
by default, floating-point literals are treated as type double .
Line 27 sets the current drawing color to one of the predeclared Color constants
( Color.BLUE ). The Color constants are static , so they're created when class Color is
loaded into memory at execution time.
The statement in lines 35-36 makes calls to Color methods getRed , getGreen and
getBlue on the predeclared Color.MAGENTA constant. Method main of class ShowColors
(lines 8-18 of Fig. 13.6) creates the JFrame that will contain a ColorJPanel object where
the colors will be displayed.
Software Engineering Observation 13.1
To change the color, you must create a new Color object (or use one of the predeclared
Color constants). Like String objects, Color objects are immutable (not modifiable).
 
Search WWH ::




Custom Search