An Applet with Mouse Events


The applet's real estate is the area within the border

Source

AnAppletWithMouseEvents.java:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class AnAppletWithMouseEvents extends Applet implements MouseListener {
    public void init() {
        addMouseListener(this);
		}

    public void mouseClicked(MouseEvent e) {
        String clickDesc;
        if (e.getClickCount() == 2)
            clickDesc = "double";
        else
            clickDesc = "single";

        System.out.println("Mouse was " + clickDesc + "-clicked at location (" +
            e.getX() + ", " + e.getY() + ")");
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
}

Notes

Working with the Mouse

This Applet's Behavior

Things to Do

API work Playing With the Applet Place the following applets on the same page:
  1. Modify the AnAppletWithMouseEvents so that:
    • A rectangle is drawn on the applet (you can, but needn't bother with a Canvas)
    • If the mouse is clicked within the rectangle, toggle between drawing and filling the rectangle
    • If the mouse is clicked outside the rectangle, toggle the background color of the applet.
  2. Same #1 (i.e., draw a rectangle on the applet), but this time instead of toggling colors, the rectangle should move whenever the user clicks inside its boundaries. (Try to have the rectangle jump to a position so that the mouse it OUTSIDE the rectangle.)