I’m trying to draw an Image with Java, I’ve the next code:
public void draw(Graphics g) {
Image strike_mid;
strike_mid = Toolkit.getDefaultToolkit().getImage(getClass().getResource("strike_mid.gif"));
for (int i=0;i<30;i++) {
for (int j=0;j<30;j++) {
if (strikeGrid[i][j]) {
g.drawImage(strike_mid, i*10, j*10, null);
}
}
}
}
The first time when I call the draw method, it doesn’t draw the strike_mid image, while I’m very sure that there is a state in the for loop that it reaches the drawImage.
When I call the draw method a second time, the drawing succeed.
I’m sure that it reaches the drawImage the first time too because when I choose to draw another .gif file, it works the first time too.
So what’s the problem here? How is it possible that with the strike_mid.gif doesn’t draw the first time?
Just because the
getImagecall fromToolkitreturns, doesn’t mean the image is fully loaded yet, if I remember my Swing/AWT correctly. You can look intoMediaTrackerorImageObserverto learn more about the asynchronous loads. Regardless, you should definitely pull thegetImagecall out of draw. The toolkit will probably cache the Image object, as described in the documentation, but there’s no reason to reload it over and over again.