Color can be controlled by accessing the Color class.  The Color class yields the class constants shown in the table below.  The expression Color.red gives the Color constant for red.

Images are drawn in the current color until the color is changed.  Changing the color does not affect the color of previously drawn images.


Available Colors

red
yellow
blue
orange
pink
cyan
magenta
black
white
gray
lightGray
darkGray

 g.setColor (Color.blue);
 g.drawString("Love this Java!", 120, 120);
 g.setColor (Color.orange);
 g.drawLine(50, 50, 150, 50);

This segment of code will print Love this Java! in blue and will then draw a line in orange.


Getting More Colors:

You can fine tune your colors by controlling the RGB (red/green/blue) density values.  Each of these 3 colors has 256 shades.  It is possible to "mix" a new shade of color by selecting an integer from 0 to 255 and passing it to a Color constructor.  The value 0 indicates the absence of a color in the mixture, and the value 255 indicates the maximum saturation of that color.  The color black has RGB(0,0,0) and the color white has RGB(255,255,255). 
          There are 256 * 256 *256 = 224 possible colors in this scheme.
  WOW!
 

To create your own color:

Access the PAINT program on your computer to help you decide upon your new color.
                         START
                         Programs
                         Accessories
                         Paint  
- Double click on any color at the bottom of the screen.
                                             - Choose "Define Custom Colors".
                                             - Select a color and/or use the arrows to achieve the desired color.
                                             - Copy down the RED, GREEN, BLUE numbers indicated.  These
                                                are the numbers needed to create your new Java color.
 

Create your new color by using the following code.  Replace the R, G and B with the numbers pertaining to your new color.

Color myNewBlue = new Color (R, G, B);  //creates your new color
g.setColor(myNewBlue);  //accesses your new color  (NO dot operator)
                            

Creating Random Colors:

Create a random color with RGB values:

 

int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
g.drawLine(10, 10, 56, 56);
g.setColor(randomColor);
g.fillOval(10, 50, 30, 60);
 

Be sure to use a CAPITAL G to represent green and not a small case g.  The small case g may interfere with the Graphics g references.

 


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use