views:

79

answers:

2

I'm developing a Snake game. Instead of showing moving rectangle, I'm planning to show a picture and want to move it with keystrokes.

but I can't do it with Jlabel. since labels are static in position.

Is there any way to display them as a image only??

thanx.

+1  A: 

You do not want to write a game using swing components for sprites!

Rather, what you do is create a custom control (usually deriving from JPanel or Canvas) element and then override the paint() function.

Inside your paint function you draw your image like this:

class MyClass extends JPanel{
    int x,y;
    BufferedImage myImage = ImageIO.read("mySprite.png");

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

Then in your code you change the values of x and y to move your sprite.

Chad Okere
What version of Java is this example using? ImageIO.read does not seem to have an implementation which only takes a string in Java 6. Do you mean the variant that takes a java.io.File argument?
Ceilingfish
+2  A: 

Here you can get a component similar to PictureBox component in .NET. Maybe that can help you achieve what you want.

missingfaktor