We're going to need a way to pause our program so that we can control how long each picture displays. Here's a handy method:
void pause(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { } }It causes your program to pause for the number of milliseconds that you pass in via the parameter time. try and catch will be explained in class.
Here's code to show two images alternately, each showing for 150 milliseconds:
currentpic = scratch1; repaint(); pause(150); currentpic = scratch2; repaint(); pause(150);
This works because the paint(Graphics g) method is now:
public void paint(Graphics g) { if (currentpic != null) g.drawImage(currentpic, xpos, ypos, this); }
To make the alternation between picture happen numtimes times, we put the altenating pictures code in a method:
public void scratch(int numtimes) { currentpic = scratch1; repaint(); pause(150); currentpic = scratch2; repaint(); pause(150); if (numtimes == 0); // we are done -- do nothing else scratch(numtimes-1); }
So the simple answer is that it displays the alternating pictures and then
makes a call to scratch(2)
Thus scratch(3) displays the alternating pictures 4 times, and then stops.
Here's the whole program.