Computer Science 121
Assignment 8
Due: April 14, 2003

This program should use a mouse listener to draw figures on an applet.  Wherever the mouse is clicked, you should draw some figure.  It can be a circle or a polygon.  You may either draw it or have it filled in.  The figures should have different colors.  Use an ‘if’ statement to change the color each time you draw a figure.  Refer to the following program for help with this assignment.  Note, you will not need a loop in your program.  The user supplies the ‘loop’ by clicking on the mouse.
 

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

// This class uses a mouse listener to find where the mouse has been pressed.
// It then draws a square with that point as the upper left hand corner.

public class MouseFigures extends Applet
{
     private Graphics g;
     private Square redSquare;
 
     public void init ()
     {
          g = getGraphics ();
          addMouseListener (new PointListener ());
     } // method init
 
     // Inner class that is used to listen for the mouse to be pressed.
    class PointListener implements MouseListener
     {
          public void mousePressed (MouseEvent e)
          {
               int xval, yval;
               xval = e.getX ();
                yval = e.getY ();
                redSquare = new Square (Color.red, xval, yval);
                redSquare.drawSquare (g);
           } // method mousePressed
 
       public void mouseEntered (MouseEvent e)  {}
       public void mouseExited (MouseEvent e) {}
       public void mouseReleased (MouseEvent e) {}
       public void mouseClicked (MouseEvent e) {}
     } // class PointListener
} // class MouseFigures

class Square
{
     private int x, y, side;
     private Color color;
 

     Square (Color c, int xPosition, int yPosition)
     {
          color = c;
        x = xPosition;
        y = yPosition;
        side = 50;
     } // constructor
 
     public void drawSquare (Graphics g)
     {
          g.setColor (color);
          g.fillRect (x, y, side, side);
     } // method drawSquare
} // class Square