0

2 つのタイマーが必要です。1 つはゲームを実行するためのものです。たとえば、オブジェクトを動かしたり、チェックを実行したり、もう 1 つはカウントダウン タイマーとして実行したりします。私は次のことを試しました:

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

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 に答える
0

javax.swing.Timerクラス を使用していると思いますか?this.actionPerformed(this);あなたのアプレットはActionEvent. さらに、init()メソッドでタイマーを開始する必要があります。

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
        }
    }
}

Timers に関する Java チュートリアルにもリダイレクトされるTimer javadocを確認してください。

于 2013-06-22T06:18:12.580 に答える