Hi
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:
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();
}
}
}
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?
Thanks
Ben