我正在寻找另一个线程,以便以秒为单位跟踪游戏时间。这里的线程是10ms,以便动画顺利移动,但由于游戏时间没有以10ms运行,我显然需要以某种方式跟踪它,但不知道在这种情况下如何做到这一点。
我有以下内容:
public class Test extends JPanel {
public int time;
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Collision Tester");
Test game = new Test();
frame.add(game);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.repaint();
//game.time++; should not be here
game.red();
Thread.sleep(10);
}
}
}
答案 0 :(得分:2)
您不需要其他线程。相反,请使用System.nanoTime()
long timeBefore = System.nanoTime();
// Some code here
long timePassed = System.nanoTime() - timeBefore;
timePassed
变量将包含经过的纳秒的数量。如果需要,可以使用TimeUnit
常量转换为其他单位。
答案 1 :(得分:1)
class gameTimer extends Thread {
int gameTime; // time in miliseconds
// This is the entry point for the second thread.
void start()
{
gameTime=0;
this.start(); //starts the thread by runing the run function.
}
}
public void run() {
while(1==1){
try{
gameTime++;
thread.sleep(1); // sleeps for 1 milisecond
}
catch(exception e){}
}
}
现在,当您想要启动计时器时,只需创建一个新实例并调用start方法。 阅读本文以进一步了解多线程http://www.tutorialspoint.com/java/java_multithreading.htm
答案 2 :(得分:0)
对于初学者来说,你没有创建一个新的线程,所以循环将作为你的主要代码运行而不是它,这意味着它将阻止其他进程正常运行,这就是我要做的:
public class Test extends JPanel implements Runnable{
@Override //This will run as a new thread
public void run(){
long beforeTime;
while(true){
game.repaint();
game.red(); //Im not sure what this exactly does :P
try{
Thread.sleep(10); //Should always put in try catch as this can throw exceptions
}catch(Exception e){
e.printStackTrace();
}
System.out.println(System.currentTimeInMillis() - beforeTime);
beforeTime = System.currentTimeInMillis();
}
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Collision Tester");
Test game = new Test();
Thread counter = new Thread(game);
frame.add(game);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
counter.start() // Starts the thread
}
}
答案 3 :(得分:0)
您可以简单地创建一个变量来保存开始时间。但是,像你一样在主线程上调用Thread.sleep
并不会让你在Swing中获得愉快的体验。你最好使用计时器:
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Collision Tester");
Test game = new Test();
frame.add(game);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final long startTime = System.currentTimeMillis();
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
game.repaint();
game.time = System.currentTimeMillis() - startTime;
game.red();
}
});
}
timer.start();
}
有关详细信息,请参阅How to Use Swing Timers。