Java Reference
In-Depth Information
In the applet of Example 12-4, you could have used the method drawRect to draw a
rectangle rather than four lines. In that case, you could use the following statement:
g.drawRect(10, 10, 430, 40); //draw rectangle
The program in Example 12-5 further illustrates how to use various methods of the
Graphics class . In this example, we create a random collection of geometric shapes.
The program uses the method random of the class Math to randomly determine the
number of figures. We want to have at least 5 and at most 14 figures. Therefore, we
declare an int variable and initialize it as follows:
int numOfFigures;
numOfFigures = 5 + ( int )(Math.random() * 10); //determine the
//number of figures
For each figure, we want a random color, random anchor point, random width, and
random height. Further, we want a random shape from a set of possible options. This
applies to all figures. Therefore, we need to have a loop similar to the following:
for (i = 0; i < numOfFigures; i++)
{
//...
}
Inside the preceding loop, we determine a random color. We can use the method
random of the class Math to get red, green, and blue values between 0 and 255 and
use them to create a random color. Therefore, we need the following statements (assume
that g is a reference variable of the Graphics type):
int red;
int green;
int blue;
red = ( int )(Math.random() * 256);
//red component
green = ( int )(Math.random() * 256);
//green component
blue = ( int )(Math.random() * 256);
//blue component
g.setColor( new Color(red, green, blue));
//color for
//this figure
We also need to compute four more values for x , y , and the width and height between,
say, 0 and 200 . Furthermore, to make the program easier to modify, we use the named
constant SIZE , initialized to 200 . Thus, we need the following Java statements:
private final int SIZE = 200;
int x;
int y;
int width;
int height;
int red;
Search WWH ::




Custom Search