Java Reference
In-Depth Information
x = ( int )(Math.random() * SIZE);
//x value
y = ( int )(Math.random() * SIZE);
//y value
width = ( int )(Math.random() * SIZE);
//width
height = ( int )(Math.random() * SIZE);
//height
Now all that is left is to randomly select a shape among, say, rectangle, filled rectangle,
oval, and filled oval. So let's assign the values:
￿
0 for rectangle
￿
1 for filled rectangle
￿
2 for oval
￿
3 for filled oval
A switch statement can be used to invoke the appropriate method, as shown in the
following:
shape = ( int )(Math.random() * 4);
switch (shape)
{
case 0 :
g.drawRect(x, y, width, height);
break ;
case 1 :
g.fillRect(x, y, width, height);
break ;
case 2 :
g.drawOval(x, y, width, height);
break ;
case 3 :
g.fillOval(x, y, width, height);
break ;
}
1
2
Putting it all together, we have the Java applet shown in Example 12-5.
EXAMPLE 12-5
//Java applet to draw ovals and rectangles
import java.awt.*;
import javax.swing.*;
public class OvalRectApplet extends JApplet
{
private final int SIZE = 200;
Search WWH ::




Custom Search