Dots

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 {

  Vector theDots = new Vector();

  public void init() {
    this.addMouseListener(this);
  }

  public void mouseClicked(MouseEvent e) {
   theDots.addElement(e.getPoint());
   this.repaint();
  }
 
  // You have to implement these methods, but they don't need
  // to do anything.
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}

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

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

 }

}

Previous | Next | Top
Last Modified June 25, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@sunsite.unc.edu