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
- The basic event-handling idea should be familiar by now: register as a listener, handle the event when it
occurs, using information obtained from the corresponding
Event
object
- There are some differences to note however:
This Applet's Behavior
- The
init
Method
- simply tregisters with the applet to listen for mouse events within the applet's real estate
- The
mouseClicked
method
- determines whether the event was a single- or double- click using the MouseEvent's getClickCount method
- determines the mouse's location at the time of the click using the getX, getY methods of the MouseEvent object
- Prints out this obtained information
Things to Do
API work
Playing With the Applet
Place the following applets on the same page:
- 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.
- 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.)