Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One problem I see with the paintComponent() method is the location where you're drawing the image. My understanding is that each sprite in your game is a separate JPanel. The Graphics object (g) being passed in the paintComponent method is, therefore, different for each Sprite. You can imagine a Graphics object as a painting canvas. If you only had 1 Graphics object for the entire game, and this graphics object represented the entire game window, then your logic would be correct and everything should work.</p> <p>However, each Sprite here has its own graphics object, presumably with height and width relevant to the sprite. In this case, your paintComponent method would probably just look like:</p> <pre><code>public void paintComponent(Graphics g) { if (spriteImage != null) g.drawImage(this.spriteImage, 0, 0, getWidth(), getHeight(); // always at (0,0) } </code></pre> <p>Why? Because with your design, you're moving the Sprite, AND it's Graphics object, around the game window! The coordinates you pass to drawImage() are relative to the Graphics object; you always want to start painting in the upper-left hand corner, (0,0), of the Sprite. You're getting just a gray square because you're trying to draw the image way out of bounds of the Graphics object.</p> <p>In the long run, I don't think this approach is going to work because it's not that easy to move JPanels around inside of their parent containers (unless you're using absolute positioning). It's not really scalable either because JPanels are pretty heavyweight and take a lot of resources to create and display.</p> <p>You are probably better of having a single JPanel that represents the entire game area. Each Sprite wouldn't be a subclass of JPanel, so you don't have a paintComponent method. You could do something like this:</p> <pre><code>public class GameArea extends JPanel { private final Collection&lt;Sprite&gt; sprites; // sprites to draw public void paintComponent(Graphics g) { for(Sprite sprite : sprites) { sprite.drawOnSurface(g); } } } public class Sprite // no need to extend anything { /* Your other code looks OK */ public void drawOnSurface(Graphics surface) { surface.drawImage(image, x, y, getWidth(), getHeight()); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload