13.3. The Graphics Class

 
[Page 412 ( continued )]

12.6. The Color Class

You can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each of which is represented by an unsigned byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade ). This is known as the RGB model .

You can create a color using the following constructor:

   public   Color(   int   r,   int   g,   int   b); 

in which r , g , and b specify a color by its red, green, and blue components. For example,

 Color color =   new   Color(   128   ,   100   ,   100   ); 

Note

The arguments r , g , b are between 0 and 255. If a value beyond this range is passed to the argument, an IllegalArgumentException would throw.


You can use the setBackground(Color c) and setForeground(Color c) methods defined in the java.awt.Component class to set a component's background and foreground colors. Here is an example of setting the background and foreground of a button:

 JButton jbtOK =   new   JButton(); jbtOK.setBackground(color); jbtOK.setForeground(   new   Color(   100   ,   1   ,   1   )); 

Alternatively, you can use one of the thirteen standard colors ( black , blue , cyan , darkGray , gray , green , lightGray , magenta , orange , pink , red , white , yellow ) defined as constants in java.awt.Color . The following code, for instance, sets the foreground color of a button to red:


[Page 413]
 jbtOK.setForeground(Color.red); 

Note

The standard color names are constants, but they are named as variables with lowercase for the first word and uppercase for the first letters of subsequent words. Thus the color names violate the Java naming convention. Since JDK 1.4, you can also use the new constants BLACK , BLUE , CYAN , DARK_GRAY , GRAY , GREEN , LIGHT_GRAY , MAGENTA , ORANGE , PINK , RED , WHITE , and YELLOW .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net