There are various methods to get something to move on the screen:
Game Loop with Sleep
The basic idea is shown below. Every thing is set up properly, then the main game loop is entered. This keeps on looping until isPlaying is set to false. The loop does various updating of the game. It also draws the graphics and then sleeps for a certain amount of time. The exact amount of time depends on processing and the load on the computer. It will always be at least SLEEPTIME milliseconds, but it may be more.
/***** Constants *****/ static final int SLEEPTIME = 5; /***** Global (instance) Variables ******/ ... Ball ball; int lives = 4; boolean isPlaying = true; /****** Constructor ********/ BallAnimationSimple() { initialize(); //Main Game Loop while (isPlaying) { moveBall(); movePaddle(); checkCollisions(); drawGraphics();//all graphics is drawn here //this probably includes a jpanel.paintImmediately(0,0,SCRW. SCRH); or else just a jpanel.repaint(); try { Thread.sleep(SLEEPTIME); } catch (InterruptedException e) {} if (lives <= 0) isPlaying = false; if (time == 10) isPlaying = false; //you only have 10 seconds //a KeyListener could also be used to end the game if you type 'Q' but that wouldn't go here } JOptionPane.showMessageDialog(null, "Game Over", "The End!" , JOptionPane.PLAIN_MESSAGE); }
Timers
Java has 3 types of timers.
Note that the different timers have different syntax
Timers The Swing Timer
First of all, you have to change the main() method to look like the following.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new myConstructor();
}
});
} //end main
This ensures that the swing timer is on the same thread as the main swing graphics.
The Swing timer has the following syntax:
Timer timer = new Timer(TIMERSPEED, this); timer.start();
TIMERSPEED: is the time in milliseconds between each timer event
THIS: is where the event handler is.
there are a couple of other useful methods that timer() has:
● .stop()
● .setDelay(int delay)
● .setInitialDelay(int initialDelay)
● .setRepeats(false)
javax.swing.Timer() creates an ActionEvent, so you just do this like a normal actionListener.
If you also have JButtons on your screen you may have problems: you'll have to create separate inner classes for the different ActionListeners.
A sample actionListener method is here:
@Override public void actionPerformed(ActionEvent ev) { moveZombies(); moveWeapons(); if (player.health < 0) gameOver = true; grPanel.repaint(); }
See "Rotating an object" for an example of a timer
Threads
Threads are complicated. They are the underlying mechanism for Timers. Timers were created to simplify the process. Threads will be discussed at some unspecified point in the future possibly.