Mahesh Gupta
Mahesh Gupta

Reputation: 925

displaying an image in swing

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.

Upvotes: 4

Views: 1909

Answers (1)

Chad Okere
Chad Okere

Reputation: 4578

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.

Upvotes: 4

Related Questions