Yahoo 知識+ 將於 2021 年 5 月 4 日 (美國東岸時間) 停止服務,而 Yahoo 知識+ 網站現已轉為僅限瀏覽模式。其他 Yahoo 資產或服務,或你的 Yahoo 帳戶將不會有任何變更。你可以在此服務中心網頁進一步了解 Yahoo 知識+ 停止服務的事宜,以及了解如何下載你的資料。
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 個解答
- 9 年前最愛解答
/*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 年前
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.