viernes, 8 de abril de 2011

[Java] Move an image inside JFrame or Applet using keyboard!


This example show how to load and move one image using keyboard arrows inside a JFrame or an Applet, it's the same procedure.

It's not a good way to draw and move the images with this method, because you will see flashing the window while the image is moving, but it's the most simple way to show you how know which key was pressed and how move the image. In the next example, I will show you how to draw images using a doble buffer technique in order to avoid the flashing in the screen!.

Well, the code for this example is here:
package mx.gcross.samples;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

/**
*
* @author René Cruz - G-Cross Studio 2011
*/
public class MoveImage 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;

public MoveImage() {
setTitle("Move Image Sample");
setSize(512, 512); //set window dimension 480x320px
loadImages();
setVisible(true); //make window visible
}

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

} catch (IOException ex) {
ex.printStackTrace();
}
//asociate the keyboard listener with this JFrame
addKeyListener(this);
}

@Override
public void paint(Graphics g) {
super.paint(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 static void main(String[] args) {
new MoveImage();
}


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

3 comentarios:

  1. Hola Rene,

    El proyecto estaba alojado en hotfile que ya no existe, sera que lo aun lo tienes?

    Gracias

    ResponderEliminar
  2. Ummm...
    Can you help me with a little problem?
    package com.andreimihai.DemoGame;

    import java.awt.Canvas;

    import java.awt.Dimension;
    import java.awt.Graphics;

    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;

    import javax.imageio.ImageIO;
    import javax.swing.JFrame;

    public class Game extends Canvas implements KeyListener
    {
    private int x = 25;
    private int y = 75;
    private static final long serialVersionUID = 1L;
    public static int height=600;
    public static int width=height*16/9;

    private BufferedImage caracter;


    private JFrame frame;

    public Game()
    {
    Dimension size = new Dimension (width, height);
    setPreferredSize(size);
    frame = new JFrame();
    loadImages();
    }


    public void loadImages() {
    try {
    String pathCaracter = "imagine.jpg";
    caracter = ImageIO.read(new File(pathCaracter));
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    addKeyListener(this);

    }

    @Override
    public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(caracter, x, y, this);
    }

    public static void main (String args[])
    {
    Game game = new Game();
    game.frame.setVisible(true);
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setVisible(true);
    game.frame.setResizable(false);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setTitle("Joc");
    game.frame.setLocationRelativeTo(null);
    }
    public void keyPressed(KeyEvent e)
    {
    int c = e.getKeyCode();
    if(c == KeyEvent.VK_LEFT)
    {
    x--;
    }
    if(c == KeyEvent.VK_RIGHT)
    {
    x++;
    }
    repaint();
    }
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}

    }


    The images are not loading

    ResponderEliminar
  3. How are you referring to the images?

    Do you have an example string?

    ResponderEliminar