martes, 24 de mayo de 2011

[Java] Move dinamically images using threads in Java Applet



This sample show how to move dinamically images in some applet scene, using doble buffer technique and using threas to move one image in a specific direction.

package mx.gcross.samples;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

/**
*
* @author René Cruz - G-Cross Studio 2011
*/

public class MoveImage extends Applet {

private Image dobleBuffer;
private Graphics myGraphics;
private Image background;
private Image nave;
int cordX;
int cordY;

@Override
public void init() {
background = getImage(getDocumentBase(), "background.jpg");
nave = getImage(getDocumentBase(), "nave.png");

// Init first coordinates
cordX = (int) (Math.random() * getWidth());
cordY = getHeight();

// Init doble buffer
dobleBuffer = createImage(getWidth(), getHeight());
myGraphics = dobleBuffer.getGraphics();

//Draw images, only the first time
drawImages();
animateShip();
}

@Override
public void update(Graphics g) {
//Draw images in the new positions
drawImages();
//Draw the buffer in the screen
g.drawImage(dobleBuffer, 0, 0, this);
}

public void animateShip() {

Thread hilo = new Thread() {
@Override
public void run() {
try {
super.run();
while (true) {
// change position of Y, and validate if need calculate new coordinates of ship...
cordY--;
if (cordY < -30) {
cordX = (int) (Math.random() * getWidth());
cordY = getHeight();
}
repaint();
// make a pause for 10 milliseconds
sleep(10);
}

} catch (InterruptedException ex) {
// do something...
}
}
};
hilo.start();
}

public void drawImages() {
myGraphics.drawImage(background, 0, 0, getWidth(), getHeight(), this);
myGraphics.drawImage(nave, cordX, cordY, this);
}
}
Test the code and comment, thanks!.

If you prefer the complete code source, resources and the HTML document in a Netbeans project, Download It Here!