Gamer Java TimerTick Event

I tried to create a Java game loop using the Timer from java.util.Timer. I cannot get my game loop to execute during a timer. Here is an example of this problem. I try to move the button during the game loop, but it does not move on the timer event.

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
java timer swing game-loop
source share
2 answers

Since this is a Swing application, do not use java.util.Timer, but rather javax.swing.Timer, also known as Swing Timer.

eg.

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

in the constructor

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

and

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

First of all, Timer.schedule schedules a task for one run, not re-runs. Thus, this program can only make the button move once.

And you have a second problem: all interactions with swing components should be performed in the event dispatch thread, and not in the background thread. Read more at http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading . Use javax.swing.Timer to perform swing actions at repeating intervals.

+4
source share

All Articles