Sequences of pictures in rapid succession

Chapter: Animation
...Section: Sequences of pictures in rapid succession

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

Q. 3
So what happens if you call scratch(3)


So the simple answer is that it displays the alternating pictures and then makes a call to scratch(2)

Q. 4
So what happens if you call scratch(2)


Q. 5
So what happens if you call scratch(1)


Q. 6
So what happens if you call scratch(0)


Thus scratch(3) displays the alternating pictures 4 times, and then stops.

Q. 7
So what happens if you call scratch(347)


Q. 8
Now let's not get into a sequence of questions and answers. Tell me simply what does scratch(347) do?


Here's the whole program.


Exercise 4

Write the SleepFrame.java program so your frame behaves like this applet








Exercise 5

Try you hand at making an application like this one:








rhyspj@gwu.edu