对于我为 java 类制作的这个游戏,我希望在角落显示一个从 0
开始计数的计时器
我创建了一个代表秒的变量,==> double s =0;
我的想法是使用一个 Timer
对象,我可以每秒递增变量并在字符串上使用 repaint()
方法
但是,我误解了计时器对象的工作原理,延迟后它会快速计数到无穷大。我现在不知道该怎么办。如有提示,我们将不胜感激。
这是我的代码,感谢您的帮助:
int delay = 5000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
s=(int)s+1;
}
};
new Timer(delay, taskPerformer).start();
String t = "" + s;
g.drawString(t, 100, 100);
repaint();
最佳答案
像这样的东西怎么样:(您可能需要根据需要更改它)
boolean temp=true;
long startTime = System.nanoTime();
while(temp){
float time = (System.nanoTime()-startTime)/ 10000000.000f;
System.out.println(time);
}
关于java - 在 swing 中制作一个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364789/