October 1, 2003

Drawing Random Circles & Squares (Using Loops)



/*
Draws a circle
*/
import java.awt.*;
    import java.applet.Applet;
    import java.awt.event.*;
public class DrawCircle extends Applet implements ActionListener
{
   Button drawButton;
   
   int radius = 20;
   int x, y;
   int red, green, blue;
   
   
   public void init() {
   
      x =10;
      y = 200;
   
      red = green = blue = 0;
   
      // Draw the GUI
   
      // Create the button
      drawButton = new Button("Draw");
   
      // Add it to the applet
      add(drawButton);
   
      // Add a listener for it
      drawButton.addActionListener(this);
   }// init
   
   public void paint(Graphics g) {
   
      for (int i=0; i < 150; i = i + 3) {
      // pick a random color
        red = (int) (Math.random()*256);
        green = (int) (Math.random()*256);
        blue = (int) (Math.random()*256);
   
        // Assign random values to x, y, and radius
        // Ensure that x, y is within the bounds of the applet (400x400)
        x = (int) (Math.random()*400);
        y = (int) (Math.random()*400);
        radius = (int) (Math.random()*50);
   
        // set the drawing color to a random color
        g.setColor(new Color(red, green, blue));
        drawCircle(g,x,y,radius);
   
        /* The following can be used instead to draw a moving circle
        x = x + i;
        if (x > 400)
             x = 10;
   
        y = 200;
   
        g.setColor(Color.black);
        drawCircle(g, x, y, 20);
   
        // slow down
        for (int j = 0; j < 5000000; j++) {
        }
        g.setColor(Color.white);
        drawCircle(g, x, y, 20);
       */
       }
} //paint
   
    // Listener for button
    public void actionPerformed(ActionEvent e) {
   
        repaint();
   
    } // actionPerformed
  
   private void drawCircle(Graphics g, int x, int y, int r) {
   // Draw a circle on g centered at x, y and radius, r
   
      g.fillOval(x-r, y-r, 2*r, 2*r);
   
   } // drawCircle
   
} // DrawCircle