Note that there are some explanatory texts on larger screens.

plurals
  1. POImage comes up as just a grey square when added to JPanel
    primarykey
    data
    text
    <p>I'm working on a project for university which is essentially a re-working of the Space Invaders game with the rules changed a bit. So far I've got a main JFrame, containing a subclass of JPanel (for the background image) which contains another subclass of JPanel which I'm using for the sprites. However, when I run it the JFrame and the background JPanel work fine but then when I draw the sprite it just generates a grey square, for which I can't change the size or position. Here's the code I've got for my Sprite class:</p> <pre><code>import java.awt.*; import java.io.File; import javax.swing.*; public class Sprite extends JPanel { Image spriteImage; int speedX; int speedY; Point pos; final boolean MV_LEFT = false; final boolean MV_RIGHT = true; public Sprite(File _imageFile) { try { spriteImage = javax.imageio.ImageIO.read(_imageFile); } catch (Exception e) { /* handled in paintComponent() */ } speedX = 1; speedY = 1; pos = new Point(100,100); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (spriteImage != null) g.drawImage(this.spriteImage, this.pos.x, this.pos.y, this.getWidth(), this.getHeight(), this); } public void move(boolean direction) { if (direction == true) { this.pos = new Point((pos.x + speedX), pos.y); repaint(); } else { this.pos = new Point((pos.x - speedX), pos.y); repaint(); } } } </code></pre> <p>I'm sure there are a few things wrong in there, but for the paintComponent() method I just parroted all of the image handling tutorials I found around the internet and it still doesn't seem to work. Is there something huge I'm forgetting?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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