-2

Im trying to draw an image in java. It was working before I created a separate class just to store the images. But now I get Null pointer exception.

Main class:

Image image;
Images images; // class object
public void paint(Graphics G){
    image = images.GETImage();
    G.drawImage(image, x, y, 20,20,null);
}

protected void paintComponent(Graphics G){
    paint(G);       
}

Image Class to store images:

public Image GETImage(){
    int direction = pacman.getDirection();
    int newDirection = pacman.getDirection();
    int x = pacman.getX();
    int y = pacman.getY();

    if(direction == Constant.UP){
        ImageIcon i = new ImageIcon("src\\images\\pacman up.png");
        image = i.getImage();

        }
    return image;
}
redundant6939
  • 153
  • 3
  • 5
  • 16
  • 1
    Which line is null? and change the name of your `paint(Graphics g)` method that doesn't conflict with the paint method that already exists. Use `myPaint(...)` or something along that idea. – Hovercraft Full Of Eels Dec 03 '12 at 19:10
  • Also, if this were my app and the images are reasonably small enough, I'd read all my images in on class creation and not keep reading in the same image over and over again while the program is running. That's very inefficient. Also, are you sure the ImageIcon isn't null due to it not finding the Image. And why create an ImageIcon if you're going to be using it as an Image? – Hovercraft Full Of Eels Dec 03 '12 at 19:12
  • Please post full stack trace. – Rohit Jain Dec 03 '12 at 19:15
  • 1
    There are two many things that MIGHT be the cause. We need more code and a stack trace (and an indication where the error is occuring) – MadProgrammer Dec 03 '12 at 19:15
  • image = images.GETImage(); this is my guess for the error;) – Forty-Two Dec 03 '12 at 19:16

1 Answers1

4

your problem is here:

Image image;
Images images; // class object (this is never initiated in code snippet given)
public void paint(Graphics G){
    image = images.GETImage(); //images is null, thus calling any method on the object will throw NPE
    G.drawImage(image, x, y, 20,20,null);
}

you never initiate images thus it will throw a NPE.

Also please take note of @HovercraftFullOfEels' comments,this is important especially the naming of your method

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    Stackoverflow has an automated process that will remove the serial down-votes. One of gbtimmon's comments has been flagged as inappropriate, but likely this whole discussion will be deleted (appropriately) by moderators. – Hovercraft Full Of Eels Dec 03 '12 at 20:15
  • @HovercraftFullOfEels tell me about it i didnt even expect anything to be done +1 stackoverflow :) – David Kroukamp Dec 03 '12 at 20:19