0

我需要两个计时器。一个运行游戏,例如移动对象,执行检查,另一个作为倒数计时器。我尝试了以下方法:

Timer countdownTimer = new Timer(1000,this);
Timer gameTimer = new Timer(30,this);

public void init()
{
   this.actionPerformed(this); //add action listener to content pane
}

@Override
public void actionPerformed(ActionEvent e) 
{
    if(e.getSource() == gameTimer)
    {
        // control the game
    }

    if(e.getSource() == countdownTimer)
    {
       //decremenet the timer
    }
}

但是,当我尝试运行小程序时,这会返回 Null 指针异常。如何正确区分每个计时器并在每个计时器滴答时执行所需的操作。谢谢

4

2 回答 2

0

I'm assuming you're using the javax.swing.Timer class? this.actionPerformed(this); does not seem right, as your applet is not an ActionEvent. Besides, you should start the timers in the init() method:

public class GameApplet extends Appel implements ActionListener
    public void init()
    {
        countdownTimer = new Timer(1000,this);
        gameTimer = new Timer(30,this);
        countdownTimer.start();
        gameTimer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == gameTimer) {
            // control the game
        }

        if(e.getSource() == countdownTimer) {
           //decremenet the timer
        }
    }
}

Check the Timer javadoc that also redirects to the Java tutorial about Timers.

于 2013-06-22T06:18:12.580 回答
0

使用 ScheduledExecutorService。它比计时器更有效。要查看其效果,请运行以下代码。

class GameControl {
    private final ScheduledExecutorService scheduler =
            Executors.newScheduledThreadPool(1);

    public void beepForGame() {
        final Runnable beeper = new Runnable() {
            @Override
            public void run() {
                System.out.println("Game");
            }
        };
        final ScheduledFuture<?> beeperHandle =
                scheduler.scheduleAtFixedRate(beeper, 30, 30, SECONDS);
        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                beeperHandle.cancel(true);
            }
        }, 60 * 60, SECONDS);
    }

    public void beepCountDown() {
        final Runnable beeper = new Runnable() {
            @Override
            public void run() {
                System.out.println("count down");
            }
        };
        final ScheduledFuture<?> beeperHandle =
                scheduler.scheduleAtFixedRate(beeper, 1, 1, SECONDS);
        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                beeperHandle.cancel(true);
            }
        }, 60 * 60, SECONDS);
    }
    public static void main(String[] args) {
        GameControl bc=new GameControl();
        bc.beepCountDown();
        bc.beepForGame();
    }
}
于 2013-06-22T06:27:43.923 回答