GAMES LESSON SEVEN: Triggering Animation with the Keyboard
In this applet the user can trigger a five frame animation by hitting the
ENTER key on the keyboard. The code that makes this possible is an
anonymous, inner-class contained in the init method:
requestFocus();
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_ENTER){
loop=0;
frameIndex=0;
}
}
});
As you can see, each time the user hits the enter key the values of loop and
frameIndex are set to zero. In the run method the value of loop is
continuously checked and when it is less than five a frame of the push up
animation is drawn.
TRIGGER.java
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;
public class TRIGGER extends Applet implements Runnable{
int dur[] = { 200, 300, 400 , 500 , 100 };
String titles[] = { "down.jpg", "mid.jpg", "up.jpg" , "mid.jpg", "down.jpg" };
Dimension d;
boolean iload=false;
Image offI;
Image currImage;
ArrayList frames;
int pnum, inum, frameIndex;
int delay = 3000;
int loop;
Thread tt;
public void init(){
d = getSize();
frames = new ArrayList();
offI=createImage(d.width,d.height);
currImage = getImage(getDocumentBase(), "images/down.jpg");
tt = new Thread(this);
tt.start();
requestFocus();
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_ENTER){
loop=0;
frameIndex=0;
}
}
});
}
public void loadImage(int c){
addFrame(getImage(getDocumentBase(), "images/"+titles[c]), dur[c]);
}
public void addFrame(Image i, int d){
frames.add(new AnimFrame(i, d));
}
public synchronized Image getImage(){
if(frames.size() == 0) return null;
else return getFrame(frameIndex).image;
}
private AnimFrame getFrame(int i){
return (AnimFrame)frames.get(i);
}
public synchronized int getDelay(){
if(frames.size() == 0) return 2000;
else return getFrame(frameIndex).duration;
}
public void run(){
while(true){
if(loop<5){
repaint();
if(iload==false){
loadImage(inum);
inum++;
if(inum>4) iload=true;
}
else{
currImage=getImage();
delay = getDelay();
frameIndex=(frameIndex+1)%4;
loop++;
}
}
try{
Thread.sleep(delay);
}catch(InterruptedException ie){
}
}
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
Graphics offG = offI.getGraphics();
offG.setColor(Color.yellow);
offG.fillRect(0,0,d.width,d.height);
if(iload){
offG.drawImage(currImage,0,0, null);
offG.setColor(Color.blue);
if(loop>4) offG.drawString("Press enter to do push up.", 30,100);
else offG.drawString("DELAY: " + delay, 30, 100);
}
else{
offG.setColor(Color.blue);
offG.drawString("Loading images..." + inum, 30, 100);
}
g.drawImage(offI,0,0,this);
}
private class AnimFrame{
Image image;
int duration;
public AnimFrame(Image i, int dur){
image=i;
duration = dur;
}
}
}
ASSIGNMENT: