Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
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?
2 Answers
- 9 years agoFavorite 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
- deonejuanLv 79 years ago
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.