4

java.util.Timerのタイマーを使用してJavaでゲームループを作成してみました。タイマーティック中にゲームループを実行できません。この問題の例を次に示します。ゲームループ中にボタンを動かそうとしていますが、タイマーティックイベントでボタンが動いていません。

import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JButton;

public class Window extends JFrame {

    private static final long serialVersionUID = -2545695383117923190L;
    private static Timer timer;
    private static JButton button;

    public Window(int x, int y, int width, int height, String title) {

        this.setSize(width, height);
        this.setLocation(x, y);
        this.setTitle(title);
        this.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        timer = new Timer();
        timer.schedule(new TimerTick(), 35);

        button = new JButton("Button");
        button.setVisible(true);
        button.setLocation(50, 50);
        button.setSize(120, 35);
        this.add(button);
    }

    public void gameLoop() {

        // Button does not move on timer tick.
        button.setLocation( button.getLocation().x + 1, button.getLocation().y );

    }

    public class TimerTick extends TimerTask {

        @Override
        public void run() {
            gameLoop();
        }
    }
}
4

2 に答える 2

9

これは Swing アプリケーションであるため、java.util.Timer ではなく、Swing タイマーとも呼ばれる javax.swing.Timer を使用してください。

例えば、

private static final long serialVersionUID = 0L;
private static final int TIMER_DELAY = 35;

コンストラクターで

  // the timer variable must be a javax.swing.Timer
  // TIMER_DELAY is a constant int and = 35;
  new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        gameLoop();
     }
  }).start();

   public void gameLoop() {
      button.setLocation(button.getLocation().x + 1, button.getLocation().y);
      getContentPane().repaint(); // don't forget to repaint the container
   }
于 2011-04-30T21:48:05.017 に答える
4

まず、Timer.schedule は、タスクを繰り返し実行するのではなく、1 回実行するようにスケジュールします。したがって、このプログラムはボタンを 1 回しか動かせません。

そして、2 つ目の問題があります。swing コンポーネントとのやり取りはすべて、バックグラウンド スレッドではなく、イベント ディスパッチ スレッドで行う必要があります。詳細については、 http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threadingを参照してください。javax.swing.Timer を使用して、一定間隔でスイング アクションを実行します。

于 2011-04-30T21:52:35.933 に答える