Skip to main content

drawing images in a JPanel

3 replies [Last post]
frankgalax
Offline
Joined: 2011-01-10
Points: 0

Hello to all,
I've been trying to draw more than 1 image in the same JPanel using a Graphics2D object and its drawImage() method. My idea is to fill my JPanel of a grid of 50x50 px images. My project is a 2D game, so the grid would be the sprites of the maps. Unfortunely when i draw a new image in the main JPanel, the images that i drew before disappear, leaving only the last drawn image in the JPanel. Is there a way to keep all the images printed on the screen?
Thank you,

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17
Points: 0

Most likely you are doing the custom painting incorrectly. Search for "Java Swing custom painting tutorial" for how to do it correctly.

frankgalax
Offline
Joined: 2011-01-10
Points: 0

Thank you for your reply,
As you said, i wasn't doing it correctly. I needed to paint the whole map in the same call of the paint(Graphics g); method. And when i call the repaint(); it will again repaint the whole thing. I thought you could only repaint the area that had been modified.

walterln
Offline
Joined: 2007-04-17
Points: 0

Since you're using Swing you should be painting in paintComponent() not paint(). And yes, you only have to paint the modified area. Specify in when calling repaint by using the repaint(x, y, width, height) overload and use graphics.getClipBounds() in paintComponent to get the dirty area.