Simple Animation of Objects - paint only

                      Next      RBA.java      Utils.java      Utility classes      Home

// Draw 8 dots at home positions.  Drag dots, with, mouse to another position.
// Release mouse button and dots return to home position.  Last "touched" dot
// is always brought to the top (draws over all other dots).
// Observe the object trails as they are moved from home positions.

// MyObjectList is a doubly linked list of cells holding Dot objects
// Its purpose is to support the illusion that one dot is "on top of" another.
// The head of the list holds the dot that is on the "bottom" and the tail holds
// the dot that is on the "top".  Searching for a dot when the mouse button is
// pressed starts from the tail.  But drawing dots starts from the head. Hence
// a doubly linked list is most efficient.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class RBAFrame extends JFrame implements Runnable, MouseMotionListener {
   Thread runner;
   Dot pick;
   Color color;
   MyObjectList mol;
   
   public RBAFrame () {
      double r = 150;
      double pi = 355.0/113.0;
      double c = 1.0/16.0;
      int x,y;
      mol = new MyObjectList();
      
      for (int i=0 ; i < 8 ; i++, c+=0.125) {
         color = Color.getHSBColor((float)c, (float)1.0, (float)1.0);
         x = (int)(r*(Math.sin(c*2*pi)+1.8));
         y = (int)(r*(Math.cos(c*2*pi)+1.35));
         mol.add(new Dot(i+1,color,x,y));
      }

      addMouseListener(ma);
      addMouseMotionListener(this);
   }

   public void start () {
      runner = new Thread(this);
      runner.start();
   }

   public void run() {
      while (true) {
	 try {  runner.sleep(100);  }  catch (Exception e) { }
         repaint();           // repaint() calls paint(Graphics)
      }
   }
   
   public void paint(Graphics g) {
      FontMetrics fm = g.getFontMetrics();
      mol.display(g, fm);  
   }

   public void mouseMoved (MouseEvent event) {  }
   
   public void mouseDragged (MouseEvent event) {
      if (pick != null) pick.setPosition(event.getX(),event.getY());
   }

   MouseAdapter ma = new MouseAdapter() {
      public void mousePressed (MouseEvent event) {
         pick = mol.findAndMoveToTop(event.getX(),event.getY());
         if (pick != null) {
            pick.setDiff(event.getX(),event.getY());
            pick.suspend();
         }
      }
      
      public void mouseReleased (MouseEvent event) {
         if (pick == null) return;
         pick.resume();
         pick = null;
      }
   };
}

public class RBA extends Applet {
   public void init () {
      RBAFrame rba = new RBAFrame();
      rba.setSize(600,500);
      rba.setVisible(true);
      rba.start();
   }
}