Kaj
Kaj

Reputation: 2503

Java image draws only second time

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?

Upvotes: 0

Views: 181

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

As mentioned by Tom, the Toolkit methods are typically asynchronous. Alternately use ImageIO.read(File/URL/InputStream) for a blocking method for loading images.

Upvotes: 1

Thorn G
Thorn G

Reputation: 12766

Just because the getImage call from Toolkit returns, doesn't mean the image is fully loaded yet, if I remember my Swing/AWT correctly. You can look into MediaTracker or ImageObserver to learn more about the asynchronous loads. Regardless, you should definitely pull the getImage call 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.

Upvotes: 3

Related Questions