viernes, 8 de abril de 2011

[Java] Move images inside JFrame using Doble Buffer Technique

Here is an example of how to draw and move images inside JFrame using the Doble Buffer technique and BufferStrategy model.

This technique is used to avoid the flicker in the screen when an image is moving. In case of Applets the doble buffer technique is different, see the next example.

The code here:
package mx.gcross.samples;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

* @author René Cruz - G-Cross Studio 2011
public class DobleBufferJFrame extends JFrame implements KeyListener {

//Objects for images
private BufferedImage background;
private BufferedImage bird;
//First coordinates of bird image
private int cordX = 50;
private int cordY = 250;
//Objects for doble buffer
private BufferStrategy myBuffer;

public DobleBufferJFrame() {
setTitle("Doble Buffer Image Sample");
//set window dimension 480x320px
setSize(512, 512);
//load images...
//make window visible
//Ignore OS paint calls

//create a doble buffer objects
//NOTE: It's very important to create bufferStrategy after
//JFrame is visible, in other case fail!
myBuffer = this.getBufferStrategy();
//call explicit to paint first time

public void loadImages() {
try {
//path for image file
String pathBackground = "images/background.jpg";
background = File(pathBackground));
String pathBird = "images/bird.png";
bird = File(pathBird));

} catch (IOException ex) {
//asociate the keyboard listener with this JFrame

public void drawImages(Graphics2D g) {
//draw brackground image (first image)
g.drawImage(background, 0, 0, this);
//draw bird image (second image, in this order)
g.drawImage(bird, cordX, cordY, this);

public void paint(Graphics g) {
Graphics2D g2 = null;
if (myBuffer != null) {
try {
//get the graphics2d object of the buffer
g2 = (Graphics2D) myBuffer.getDrawGraphics();
//draw images in buffer
} finally {
//draw the content of buffer in the screen;

public static void main(String[] args) {
new DobleBufferJFrame();

//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 ++;

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

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

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

//call explicit to paint


//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 and resources in a Netbeans project, Download It Here!

No hay comentarios:

Publicar un comentario