For example, let's suppose you want an applet that draws a red circle wherever the user clicks the mouse. Recall that applet's are subclasses of java.awt.Component. Therefore you need to install a MouseListener on your applet that responds to mouse clicked events. In an applets of this nature it's simplest just to make the applet itself the MouseListener.

In this case, since you need to store the points clicked in a Vector, it's most convenient to use getPoint(). The coordinates are relative to the component to which this event is directed, not necessarily the global coordinate system of the applet (though in this case they're the same thing).

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

public class Dots extends Applet implements MouseListener {

  private Vector theDots = new Vector();

  public void init() {

  public void mouseClicked(MouseEvent evt) {
  // You have to implement these methods, but they don't need
  // to do anything.
  public void mousePressed(MouseEvent evt) {}
  public void mouseReleased(MouseEvent evt) {}
  public void mouseEntered(MouseEvent evt) {}
  public void mouseExited(MouseEvent evt) {}

  // paint the dots
  public void paint(Graphics g) {

    Enumeration e = theDots.elements();
    while (e.hasMoreElements()) {
      Point p = (Point) e.nextElement();
      g.drawOval(p.x, p.y, 5, 5);



Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2006 Elliotte Rusty Harold
Last Modified April 18, 2005