Write a program that has a GRect (which represents a stamp) follow a users mouse around and draw a GRect on the screen centered around the mouse when the user clicks

Remember that since you need to have a variable that you can change inside a mouse event class (the GRect which represents your stamp) you are going to have to declare it as an instance variable. Ask one of the teachers to explain this if it doesn't make sense.

Solution

/**
 * Class: StampTool
 * -----------------
 * Stamps a square stamp wherever the user clicks.
 */
public class StampTool extends GraphicsProgram {

    private static final int SIZE = 50;

    private GRect stamp = new GRect(SIZE, SIZE);

    public void run() {
        stamp.setColor(Color.BLUE);
        stamp.setFilled(true);
        add(stamp);
        addMouseListeners();
    }

    public void mouseClicked(MouseEvent e) {
        int x = e.getX() - SIZE / 2;
        int y = e.getY() - SIZE / 2;

        GRect r = new GRect(SIZE, SIZE);
        r.setFilled(true);
        add(r, x, y);
    }

    public void mouseMoved(MouseEvent e) {
        int x = e.getX() - SIZE / 2;
        int y = e.getY() - SIZE / 2;
        stamp.setLocation(x, y);
    }
}