Creating a simple animation

 

We can create simple animations by introducing timing delays between drawing operations.  This can be accomplished by the method pause, which has two forms: the first one with no parameters will pause for 10 milliseconds, and the second with an integer parameter that represents the number of milliseconds to pause.  By turning adjacent cells on and off we can create the illusion of motion.  The following program is a simple example. 

 

public class Animate1

{

  public static void main(String[] args)

  {

    // create a 5x3 board and animate a cell across the middle row

    Board b = new Board(5, 3);

    b.turnOn(0, 1);

    // 500 msec is long enough to make it reasonably slow

    b.pause(500);

    b.turnOff(0, 1);

    b.turnOn(1, 1);

    b.pause(500);

    b.turnOff(1, 1);

    b.turnOn(2, 1);

    b.pause(500);

    b.turnOff(2, 1);

    b.turnOn(3, 1);

    b.pause(500);

    b.turnOff(3, 1);

    b.turnOn(4, 1);

  }

}

 

As you can see, the code simply repeats a sequence of three operations, turnOn, pause and turnoff while varying the cell coordinate every time.  You can imagine how long the code would become had the board object been much bigger (100 columns).  Luckily, there’s a structure in Java that allows us to deal with such repeated executions of code called a loop.  Loops will be the subject of the next unit.