viernes, 8 de abril de 2011

[Java] Draw & moving images inside an Applet using Doble Buffer Technique


Hi, this is the example of how implements the double buffer technique in an Applet, because the procedure it's very different compared with JFrame method.

In this case, I used an instance of Image class to draw in memory all scene, after we will paint it in a single step, this avoid the flicker in the screen when the image is moving.

NOTE: Remind to create a HTML document to use this Applet.

The code of Applet is here:

package mx.gcross.samples;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
*
* @author René Cruz - G-Cross Studio 2011
*/
public class DobleBufferApplet extends Applet implements KeyListener {
//Empty image for doblebuffer
private Image dobleBuffer;
private Graphics myGraphics;

private Image background;
private Image bird;
int cordX = 20;
int cordY = 30;

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

addKeyListener(this);

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

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

@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 drawImages() {
myGraphics.drawImage(background, 0, 0, getWidth(), getHeight(), this);
myGraphics.drawImage(bird, cordX, cordY, this);
}

//While a key is pressed
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
//if the right arrow in keyboard is pressed...
case KeyEvent.VK_RIGHT: {
cordX +=3;
}
break;

//if the left arrow in keyboard is pressed...
case KeyEvent.VK_LEFT: {
cordX -=3;
}
break;

//if the down arrow in keyboard is pressed...
case KeyEvent.VK_DOWN: {
cordY +=3;
}
break;

//if the up arrow in keyboard is pressed...
case KeyEvent.VK_UP: {
cordY -=3;
}
break;

}
//call explicit to paint
repaint();


}

//When a key is typed (once)
public void keyTyped(KeyEvent ke) {
}

//When a key is released (typed or pressed)
public void keyReleased(KeyEvent ke) {
}
}

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!

No hay comentarios:

Publicar un comentario