Display image in a swing

I am developing a Snake game. Instead of showing a moving rectangle, I plan to show the image and want to move it using the keys.

but i cant do it with jlabel. as labels are static in position.

Can I only display them as an image?

thanks.

+4
source share
1 answer

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

Most likely, you create a user control (usually obtained from JPanel or Canvas), and then override the paint () function.

Inside your drawing function, you draw your image as follows:

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 x and y values ​​to move the sprite.

+4
source

All Articles