Software School Projects | Academic Students Projects | Source Codes | Tablets header
Please use our contact us form or send email to Support@srishtis.com.

Animating Applet using threads
The main idea of the applets animation is to use a new Java thread that contains an animation loop. The animation loop is responsible for keeping track of the current frame and for requesting periodic screen updates. To implement a thread, we must either create a subclass of Thread or adhere to the Runnable interface.
import java.awt.*;
import java.applet.Applet;


public class AppletAnimatorSimple extends java.applet.Applet implements Runnable {


int frame;
int delay;  
Thread animator;


// Initialize the applet and compute the delay between frames.  
 
 
public void init() {


String str = getParameter("fps");  
int fps = (str != null) ? Integer.parseInt(str) : 10;  
delay = (fps > 0) ? (1000 / fps) : 100;  
}  

// 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 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;  
}  

// 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 startTime = System.currentTimeMillis();  

//This is the animation loop.  

while (Thread.currentThread() == animator) {

//Advance the animation frame.

frame++;  

//Display it.  

repaint();  

//Delay depending on how far we are behind.  

try 
{
startTime +=delay;
Thread.sleep(Math.max(0, startTime-System.currentTimeMillis()));
} 

catch (InterruptedException e)
{ 
break; 
}  
}   
} 

//Draw the current frame of animation.  

public void paint(Graphics g) {
g.drawString("Frame: " + frame, 30, 30);
}   
}  
   

 
 
Job or extra money for students

Search Engine Rank of your blog or websites