The flickering has gone away now ;D
This is the sprite class (below), it is not perfect but it works fine, I still want to change the timer to a thread.
Can anyone recommend other improvements?
public class Sprite extends Component {
private int frameDelay;
private int frames;
private BufferedImage[] images;
private Timer timer;
private int imageIndex = 0;
private String imageDir;
private int imageWidth;
private int imageHeight;
public Sprite(final int delay, final String imageDir) {
this.frameDelay = delay;
this.imageDir = imageDir;
this.initSprite();
}
public void initSprite() {
this.setImages(loadImages());
timer = new Timer(this.frameDelay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
imageIndex = (imageIndex + 1) % Sprite.this.frames;
repaint();
}
});
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
try {
g.drawImage(this.getImages()[imageIndex], 0, 0, this);
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
}
private List<String> getFileList() {
// read all image names from the .list file
File f = new File("images/" + this.imageDir + "/img.list");
List<String> fileList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line = null;
while ((line = reader.readLine()) != null) {
fileList.add(line);
}
reader.close();
// set the frames for reference
this.setFrames(fileList.size());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return fileList;
}
private BufferedImage[] loadImages() {
List<String> fileList = getFileList();
// load the images into the image buffer
BufferedImage[] images = new BufferedImage[fileList.size()];
for (int j = 0; j < this.getFrames(); j++) {
try {
File file = new File("images/" + this.imageDir + "/" + fileList.get(j));
images[j] = ImageIO.read(file);
//System.out.println("Loaded: " + "images/" + this.imageDir + "/" + fileList.get(j));
} catch (IOException ioe) {
System.out.println("read trouble: " + ioe.getMessage());
}
}
//get the dimensions
this.imageWidth = images[0].getWidth(this);
this.imageHeight = images[0].getHeight(this);
return images;
}
…getters and setters here