This is in response to a question in a comment on one of my scenarios.
The code I used for the Timer class follows:
The timer starts the moment the timer object is created and only has a 'stop' method. It can easily by complimented with methods like 'start', 'reset', 'getText', 'setText', 'getElapsedTime', etc. or modified to not start until the 'start' method (which needs added) is called.
import greenfoot.*;
import java.awt.Color;
public class Timer extends Actor
{
String text = "";
boolean stopped = false;
double startTime, lastTime = 0;
String elapsedTime = "0.0";
public Timer(String whose)
{
text = whose;
updateImage();
startTime = System.currentTimeMillis();
}
private void updateImage()
{
setImage(new GreenfootImage(text + ": " + elapsedTime, 30, Color.black, new Color(0, 0, 0, 0)));
}
public void act()
{
if (!stopped)
{
double now = System.currentTimeMillis();
double span = now - startTime;
span = (span - (span % 100)) / 100;
if (span == lastTime) return;
lastTime = span;
elapsedTime = "0000" + (span / 10.0);
while (elapsedTime.length() > 3 && elapsedTime.startsWith("0")) elapsedTime = elapsedTime.substring(1);
updateImage();
}
}
public void stop()
{
stopped = true;
}
}
