Domanda

Ho provato a fare un loop di gioco in Java usando il timer da java.util.timer. Non sono in grado di eseguire il mio loop di gioco durante il segno di spunta. Ecco un esempio di questo problema. Sto cercando di spostare il pulsante durante il ciclo di gioco, ma non si sta muovendo sull'evento di spunta del timer.

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();
        }
    }
}
È stato utile?

Soluzione

Dal momento che questa è un'applicazione swing, non utilizzare un java.util.timer ma piuttosto un javax.swing.timer noto anche come timer swing.

per esempio,

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

nel costruttore

  // 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();

e

   public void gameLoop() {
      button.setLocation(button.getLocation().x + 1, button.getLocation().y);
      getContentPane().repaint(); // don't forget to repaint the container
   }

Altri suggerimenti

Prima di tutto, Timer.Schedule pianifica l'attività per un'esecuzione, non per esecuzioni ripetute. Quindi questo programma può far muovere il pulsante solo una volta.

E hai un secondo problema: tutte le interazioni con i componenti swing devono essere eseguite nel thread di spedizione eventi e non in un thread di fondo. Leggi http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#Threading per ulteriori dettagli. Usa un javax.swing.timer per eseguire azioni swing a intervalli ripetuti.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top