Using the Breadboard Timer

In several of the breadboard classes (e.g., OneButtonBreadboard), there is a built-in timer that allows a block of code to be executed every $n$ milliseconds, once it has been started.

The following provides an example:

import java.awt.Color;

import acm.breadboards.OneButtonBreadboard;
import acm.graphics.GOval;

public class Blinker extends OneButtonBreadboard {
	
	// if we want access to a variable in all of the methods below
	// we declare it up here [ inside the class, but outside of run() ]..
	GOval circle; 
	int tickNum;  
	
	public void run() {
		// build a circle (i.e., a GOval) and add it to the canvas..
		circle = new GOval(200,200);
		circle.setFilled(true);
		circle.setFillColor(Color.BLUE);
		this.add(circle);
		
		// keep track of what tick you are on with "tickNum"
		tickNum = 0;
		
		this.pause(2000);  // pause for 2 seconds (2000 milliseconds)
		
		// set up timer and start it..
		this.getTimer().setDelay(300);  // sets delay between 
                                                // "timer ticks" to be 
                                                // 300 milliseconds

		this.getTimer().start(); // starts the timer "ticking"
	}
	
	public void onTimerTick() {
		// with each tick of the timer, change the color of the circle
		tickNum++;
		circle.setFillColor(tickNum % 2 == 0 ? Color.RED : Color.GREEN);
	}

}