Jumping Jack
Get this applet running. (Read the comments carefully.)
import java.awt.*;
import java.applet.*;
import java.awt.event.*; //necessary for events
public class jack extends Applet{
int i;
public void init(){
setBackground(Color.black);
requestFocus(); //first step to take keyboard input
this.addKeyListener(new KeyAdapter(){ //second step to take kb input
public void keyPressed(KeyEvent k){
i++; //advances frame
i=i%8; //modulus to recycle at i==8
repaint(); //redraw
}
});
}
public void drawJack(Graphics g){ //drawJack method
// the || means OR
int s=50;
g.drawOval(s-10, 20, 20, 20); //always draw this
g.drawLine(s,40,s,60); //always draw this
//draw only one of the following:
if(i==2 || i==6){ //frame 3 and 7
g.drawLine(s-20,45,s+20,45);
g.drawLine(s,60,s-15,82);
g.drawLine(s,60,s+15,82);
}
else if(i==3 || i==5){ //frame 4 and 6
g.drawLine(s,45,s+18,37);
g.drawLine(s,45,s-18,37);
g.drawLine(s,60,s-20,81);
g.drawLine(s,60,s+20,81);
}
else if(i==4){ //frame 5
g.drawLine(s,45,s+16,30);
g.drawLine(s,45,s-16,30);
g.drawLine(s,60,s-25,78);
g.drawLine(s,60,s+25,78);
}
else if(i==1 || i==7){ //frame 2 and 8
g.drawLine(s,45,s+15,53);
g.drawLine(s,45,s-15,53);
g.drawLine(s,60,s-12,84);
g.drawLine(s,60,s+12,84);
}
else{ //frame 1
g.drawLine(s,45,s+10,60);
g.drawLine(s,45,s-10,60);
g.drawLine(s,60,s-6,85);
g.drawLine(s,60,s+6,85);
}
}
public void paint(Graphics g){
g.setColor(Color.yellow);
g.drawRect(10, 10, 80, 80);
drawJack(g); //calls drawJack method
}
}
//When the user presses any key the value of i is incremented. Then
//the value of i is recycled to 0 if it reaches 8. Next the image is redrawn
//and Jack is redrawn depending on the value of i.