paintComponent invoked many times

43 Views Asked by At

I'm creating a shooting game. When the bullet (which is a JLabel) passes through the enemy (which is a JPanel) then the paintComponent() method gets invoked until the bullet has passed through the enemy... why is that? My guess is that the paintComponent() method gets invoked by default when two components pass through, is that correct ? ( I have not used any collision detection in my code yet.)

1

There are 1 best solutions below

0
Hovercraft Full Of Eels On

The paintComponent method calls are often initiated by the OS or the Swing painting engine whenever a portion of your GUI has "dirty pixels" and needs to be repainted. You may also suggest that it be called by calling repaint().

Bottom line is: you do not have direct control over when or even if it will be called, and so your program logic should not depend on its being called at a precise moment. The method should have one job and one job only: to visually display the state of your program. The method itself should not be involved with changing your GUI's model (the logic that underpins the GUI) in any way.

That being said, you will want to change/improve your program structure:

  • Your bullet shouldn't be a JLabel
  • Your "enemy" should not be a JPanel
  • Rather they should be represented by logical (non-GUI) classes, and displayed as image sprites in a single JPanel that is responsible for all of your program's graphics, the JPanel that overrides paintComponent.

For details, check out: