954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

problem drawing images

I am creating a game in which I import images from files to represent characters, etc. I have created a class called Contents which represents anything that can be placed on a tile of the gameboard. A subclass of Contents (by several levels) is Wizard, to create a wizard character. I have it set up so that Contents contains several protected variables whose values are set in Wizard.

protected Tile currentTile; //The tile of the contents
protected final Toolkit tools=Toolkit.getDefaultToolkit();
protected URL url; //url of the image corresponding to the contents
protected Image image; //the image itself


In Wizard,

url=Wizard.class.getResource("Wizard.PNG");
image=tools.getImage(url);


Contents also contains a draw method to draw it on a specified tile.

public void draw(Graphics g, ImageObserver i)
{
    try
    {
        g.drawImage(image, (currentTile.getX()*30)+10, (currentTile.getY()*30)+10, 29, 29, i); //EXCEPTION
    }
    catch(NullPointerException e)
    {
        e.printStackTrace();
    }
}


I get a NullPointerException on the line where I try to draw the image. However, when I go to Wizard and print out both the URL and the image, both come out as expected. Not sure why the image is seen as being null. Any help would be awesome.

pi_lord12
Light Poster
31 posts since Jun 2010
Reputation Points: 10
Solved Threads: 1
 

What object reference is null causing the NPE?
On that line there are three object references. Which one is null?

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

Four, if you're counting the Graphics context.

jon.kiparsky
Posting Virtuoso
1,849 posts since Jun 2010
Reputation Points: 383
Solved Threads: 187
 

I can only see three: g, image and currentTile

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

i is an ImageObserver, isn't it?

jon.kiparsky
Posting Virtuoso
1,849 posts since Jun 2010
Reputation Points: 383
Solved Threads: 187
 

Yep. My glasses need cleaning. Damn single letter variables.

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

Wow... I feel like an idiot. Instead of using a method to set currentTile, I used the method to return the tile that I wanted to set it to... thanks and sorry about that!

pi_lord12
Light Poster
31 posts since Jun 2010
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: