Animation - Threads
Previous    Next    Home    Package    Source    Utils.java

Animation - Threads
  1. Drag an object to someplace other than its home position and release it. The object will return to its home position but will leave a color trail behind as it does so.
  2. Objects are created from a class called Dot (in Utils.java) which is on a thread (since it implements Runnable and the constructor has the lines runner = new Thread(this); and runner.start()). Each object has a home position given by variables x and y (set in the constructor) and a current position given by variables left and top. Dragging an object sets left and top. The thread, which comes to life every 40 milliseconds (see the run method of the Dot class) and moves (but does not draw) the object 1% closer to its home position due to:
       left = ((float)(.99*(left-x) + x));
       top  = ((float)(.99*(top-y) + y));
    
    The thread is running except when being dragged. In that case, runner.suspend() has been invoked. That is why the object does not continue to move toward home when it is being dragged. After release, runner.resume() is invoked to resume the thread.
  3. Objects are saved in an instance of MyObjectList (in Utils.java). Such a list is doubly linked: to find an object that the mouse is over, the list is traversed in one direction (for the "topmost" object) and to draw objects (one at a time) the list is traversed in the other direction ("bottommost" should be drawn first). The display method of that class invokes a paintDot method which exists for each dot. An object is drawn at its left, top coordinates.
  4. The list also has a moveToTop() method which makes a "picked" object the "topmost" object.
  5. The main class, called RBB, has another thread which invokes the display method of the MyObjectList class every 30 milliseconds to paint all the dots. Painting is accomplished via mol.display(g,fm) in method paint(Graphics g). Since nothing is erased, the new painting is done on top of the old painting which is why color trails are left.
  6. The mousePressed method of RBB invokes findAndMoveToTop, which returns the object "picked", and then suspends that object's thread.
  7. The mouseDragged method just changes the values of left and top of the "picked" object via setPosition of the Dot class.
  8. The mouseReleased method resumes the thread of the "picked" object.