File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes colors in life!!!!  :) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "colors in life!!!!  :)" Watch "colors in life!!!!  :)" New topic

colors in life!!!! :)

ankush walia
Ranch Hand

Joined: Jan 24, 2001
Posts: 95
hi everyone;
can anyone how random numbers are used to generate the different colours(selecting from Red,Green & Blue)!!i want to know how the random function works in this respect and what all functions can be performed with these colours!!
<----- SKY_IS_THE_LIMIT------>
ryan burgdorfer
Ranch Hand

Joined: Jan 24, 2001
Posts: 219
The Color class has many different constructors. The two which are easiest to use are Color( int r, int g, int b) where r, g, and b are ints in the range 0-255, and Color( float r, float g, float b) where r, g, and b are floats in the range 0.0-1.0.
Using the Math.random() function, you could either say:
int x = ( int )Math.random() * 255;
int y = ( int )Math.random() * 255;
int z = ( int )Math.random() * 255;
Color randomColor = new Color( x, y, z );
// or...
float x = ( float )Math.random();
float y = ( float )Math.random();
float z = ( float )Math.random();
Color randomColor = new Color( x, y, z );
Note that in either case, you have to cast the value produced by Math.random() to the desired value, since it normally produces a double greater than or equal to 0.0 and less than 1.0.
Hope this helps...

<UL TYPE=SQUARE><I><LI>Ryan Burgdorfer<BR><LI>Java Acolyte</I></UL>
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

Just remember if you use the 'int' version... random() returns a double value in the range 0>=x<1... If you cast this to an int it will always return 0... Make sure you cast the result of the multiplication to prevent this :


Write once, run anywhere, because there's nowhere to hide! - /. A.C.
ryan burgdorfer
Ranch Hand

Joined: Jan 24, 2001
Posts: 219
oh yeah, I did forget those parentheses, didn't I...
Operator precedence bites me in the butt often, I gotta watch that
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

I use parenthesis even if I dont have to because it makes the code easier to understand.

Visit my download page
I agree. Here's the link:
subject: colors in life!!!! :)
It's not a secret anymore!