Question

I'm trying to get an image to load in a game that I am working on. I'm patterning it after a group game we built in class. In my panel class I load an image and draw it to the background, this works, it finds my image and draws it.

However, no matter how I load the image that I am putting in my spaceship class and draw it using an instance of spaceship, it gives me a null pointer exception. It never finds the image, I am guessing, however I put it in the same location in the source folder that the background image is successfully pulled from. Also, if I load the space image in my gamescreen class and draw it to the panel it works fine.

Code for the two classes is below. I have tried loading the image with a

spaceship = ImageIO.read(new File("Background.png"));

As well as:

Image img = Toolkit.getDefaultToolkit().createImage("spaceShip.png"); 

But get the same null pointer both ways. I'm lost and hope someone can help.

package temp;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameScreen extends JFrame {

    //Create an instance of a spaceship object
    SpaceShip spaceship;

    //Create an instance of a missile object
    Missile missile;

    //Create an instance of a launcher object
    Launcher launcher;

    //create an array that holds missile objects
    ArrayList<Missile> missileArray = new ArrayList<Missile>();

    //Creates an array to hold spaceship objects
    ArrayList<SpaceShip> enemyArray = new ArrayList<SpaceShip>();

    int lives = 3;

    public GameScreen() {
        //sets up the panel and the parent frame

        //sets the default specs of the JFrame and adds the panel to it
        this.setSize(600, 700);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        //Creates a panel object and adds it to the main frame
        panel panel1 = new panel(launcher, enemyArray, missileArray);
        this.add(panel1);
    }
}

class panel extends JPanel {
    //creates a new launcher object
    Launcher launcher;

    //creates a spaceship object
    SpaceShip space;

    //creates an arraylist of spaceship objects
    static ArrayList<SpaceShip> ships;

    //creates an arraylist of missile objects
    ArrayList<Missile> missiles;

    //loads images to draw 
    Image backGround;

    public panel(Launcher la, ArrayList<SpaceShip> ss, ArrayList<Missile> mi) {
        try {
            launcher = la;
            ships = ss;
            missiles = mi;

            backGround = ImageIO.read(new File("Background.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void paintComponent(Graphics g) {
        BufferedImage x = new BufferedImage(600, 700, BufferedImage.TYPE_INT_RGB);
        Graphics g2 = x.getGraphics();

        g2.drawImage(backGround, 0, 0, this);

        g2.drawImage(space.img, 0, 0, this);

        System.out.println(ships.size());

        g.drawImage(x, 0, 0, this);
    }
}

SpaceShip.java

import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 * @author WymoreJW
 */
class SpaceShip extends Character {

    Image img = Toolkit.getDefaultToolkit().createImage("spaceShip.png");

    public void SpaceShip() {

        this.health = 10;
        this.speed = 2;
    }
}

Stack Trace error

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at missiledefense.panel.paintComponent(GameScreen.java:108)
    at javax.swing.JComponent.paint(JComponent.java:1029)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paintToOffscreen(JComponent.java:5131)

    at    javax.swing.RepaintManager$PaintManager.paintDoubleBuffered
(RepaintManager.java:1479)

    at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1410)
    at javax.swing.RepaintManager.paint(RepaintManager.java:1224)
    at javax.swing.JComponent.paint(JComponent.java:1015)
    at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
    at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
    at java.awt.Container.paint(Container.java:1780)
    at java.awt.Window.paint(Window.java:3375)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:713)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:693)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run
(SystemEventQueueUtilities.java:125)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters
(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy
(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Was it helpful?

Solution

The biggest issue is that your comments don't align with the code (semantically):

//creates a spaceship object
SpaceShip space;

This doesn't create an instance. This creates a reference to an instance--but no instance. It's null. You pass it to the (poorly-named) panel class constructor and act like there should be a value in it. But there isn't.

The NPE, or at least one of them:

g2.drawImage(space.img, 0, 0, this); // *foom*

At least in the code provided, space is never initialized.

I'd also recommend not wedging all of this into a single file.

OTHER TIPS

Your variables spaceShip, missile and launcher are all null. to instantiate a variable you need to call its constructor, e.g.

//Actually Create an instance of a spaceship object
SpaceShip spaceship = new SpaceShip();

//Actually Create an instance of a missile object
Missile missile = new Missile();

//Actually Create an instance of a launcher object
Launcher launcher = new Launcher();

If you don't do this then when the line panel panel1 = new panel(launcher, enemyArray, missileArray); is run the panel constructor will try to set launcher = la;. Problem comes here, since la is currently null.

I'd also recommend renaming your panel class to something more descriptive, or atleast to Panel (since classes in Java should always start with a capital letter).

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top