Credits

Tuesday, March 16, 2010

Java's Use of Colors

Part of Java's use of Graphics class is the use on colors. To set color to our text, we can use the code below:

graphicObject.setColor(color_constant);  

ex:

myObject.setColor(Color.pink);


To use our own color variants, we can have a constructor for color:

Color colorObject = new Color(red_extent,green_extent,blue_extent);

ex:

Color newColor = new Color(200,10,255); 

 where this constructor can create a light blue color. Then we use the same to set the text color as indicated below:

myObject.setColor(newColor);


A program below demonstrates various color variants.



[+/-] show/hide



/* sample program on graphics */

import java.applet.*;
import java.awt.*;


public class GraphicsDemoColor extends Applet {

Font littleFont = new Font("Helvetica",Font.ITALIC,6);


public void paint(Graphics gr){
int r,g,b;
int x=0,y=0;

for(r=255;r>=0;r-=20)
for(g=255;g>=0;g-=20)
for(b=255;b>=0;b-=20)
{
Color variety = new Color(r,g,b);
gr.setColor(variety);
gr.drawString("X", x, y);
x+=5;
if (x >=400)
{ x=0;
y+=10;

}
}


}
}



AddThis