Sunday, February 1, 2009

Mon Feb 2, part four: one button, many random colors!

OK, here's a final lesson of the day: how do you make the button display colors other than black? Simple: use "rgb" values, three random number generators that create values from 0 to 255, and a little thing called "typecasting". Plus, we'll make use of the "new" keyword, and the Java Color class. Allow me to explain them all first, then I'll show you how to mod your program using these new techniques:

A) rgb -- this is a way of combining values for red, green and blue to make any of about 16,000,000 colors. Each value has a range from 0 to 255

B) random numbers -- making random numbers is pretty simple in Java, and pretty close to how we did it in VB; we just invoke a method called Math.random(). We also have to have a way of chopping off all that useless stuff to the right of the decimal, and an easy way of doing that is to pass it to the Java Math.round() method. Also, we would want to multiply the result by whatever value we want to set as our highest possible number, in this case, 255.

C) typecasting -- in Java, you can convert different variable types into other compatible type by using typcasting. All you do is put the varibale type inside parantheses, like so: (int). We need to do that in our current program because the random() method doesn't create intgers, but that's what we need.

OK, so now let's mod your app, OK? Here are the steps to do it:



0) add this import statement at the top of your code:

import java.awt.Color; //allows use of rgb Color values

1) in your actionPerformed method, add these three lines:


int r = (int)Math.round(Math.random()*255);
int g = (int)Math.round(Math.random()*255);
int b = (int)Math.round(Math.random()*255);



they create three random integer values between 0 and 255 every time the button is pushed





2) In your "setBackground" method, replace everything inside the parentheses with this line of code:


new Color (r,g,b)


Essentially, you are passing those int values to a new Color object. That Color object is then passed to the setBackground method, which uses it to change the background color





Cheers,


Uncle Paulie

No comments:

Post a Comment