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;

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

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

public void animateShip() {

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

} catch (InterruptedException ex) {
// do something...

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!