我正在尝试编写一个游戏,在其中输出玩家存活的时间(以毫秒为单位)。我想我可以只使用一个计时器并很容易地获取它的值。
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(30,this); //I think it(30) should be 1 right ?
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop;
timealive=timer.value; // <--- That's what I'm looking for.
}
}
}
但是我的问题是:timer.value不存在,那么如何获取计时器的毫秒值?
最佳答案
这是我为您提供的解决方案。您需要创建每秒精确计时 1 次的计时器。当玩家还活着时,每个刻度都会增加 timealive
变量的值。我有另一个解决方案给你,但我认为这应该足够了。
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(1000,this); // 1000ms = 1 second, but you
// can also set it to 30ms.
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop();
// here we can use timealive value
} else {
// timealive++; if you want to get the value in seconds
// in this case the timer delay must be 1000ms
timealive += timer.getDelay(); // if you want to get the value in milliseconds
}
}
关于java - 获取javax swing计时器值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414854/