A useful clock in Java?

I have a program with an object that moves around the screen. What I need to have happen is, when the program starts, a timer should start. Every time the object's position is updated, it should record at what time it was updated. Then when it is updated again, it will known how long it's been since it was last updated. That way it will know how far to travel in the intervening time since it was last updated.

The only problem is I'm not sure how to implement such a timer. If you cannot tell from my description, I do not want to implement either javax.swing.Timer or java.util.Timer. I believe what I'm looking for is the Thread class but I've never used it before nor do I know if that would accomplish my goal. Can anyone point me in the correct direction?

Akatosh2012-01-29T16:48:49Z

Favorite Answer

/*I'm assuming by Object you mean a Sprite*/

public class Class {

private long lastTime;
private long miliTimeElapsed;
private int secTimeElapsed;

Class() {
lastTime = 0;
miliTimeElapsed = 0;
secTimeElapsed = 0;
}

public void updatePosition() {

Calendar calendar = new Calendar();

if(lastTime != 0) {

miliTimeElapsed = calendar.getTimeInMillis() - lastTime;
secTimeElapsed = (int) (miliTimeElapsed/1000);

}//close if block

lastTime = calendar.getTimeInMillis();

}//close updatePosition method

}//close Class class

deonejuan2012-01-30T00:52:47Z

Sounds like... you need the MouseListener (or whatever Events the Object) to invoke a method() to System.nanoTime(); The Object should have a private member ArrayList<Long> times;

public void setClock() {
times.add( new Long( System.nanoTime() );
}
or use a Deque ( Stack ) instead of ArrayList. I'm not following you on what this Object travels.