|
Timing
To do animation or anything that requires delay, you need to implement
the class runnable. The code is a little complex; it uses something
called threads to delay operating.
You need to:
- implement runnable (just add runnable after mouseListener in your implements.
- Add the code below
- The only editable section of that code is the int delay which
is in millliseconds.
public void update()
{
//put your code for what should happen each animation
}
/*********************************************************************************************/
/* BELOW IS FOR ANIMATION. THE ONLY THING THAT YOU NEED TO CHANGE IS DELAY */
int frame;
int delay=50; // this is the time of the delay in milliseconds.
Thread animator;
/**
* This method is called when the applet becomes visible on
* the screen. Create a thread and start it.
*/
public void start()
{
animator = new Thread(this);
animator.start();
}
/**
* This method is called by the thread that was created in
* the start method. It does the main animation.
*/
public void run()
{
// Remember the starting time
long tm = System.currentTimeMillis();
while (Thread.currentThread() == animator)
{
// Display the next frame of animation.
update();
try
{
tm += delay;
Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
}
catch (InterruptedException e)
{
break;
}
// Advance the frame
frame++;
}
}
/**
* This method is called when the applet is no longer
* visible. Set the animator variable to null so that the
* thread will exit before displaying the next frame.
*/
public void stop()
{
animator = null;
}
|