0

I'm getting a NullPointerException when calling drawImage() on the last line of this sample even though I'm not giving it a null variable. Help would be appreciated.

    BufferedImage image = null;
    System.out.println(image);

    try {

        image = ImageIO.read(getClass().getResource("/gameobjects/diaz.jpg"));
        System.out.println("eter");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(image);
    Graphics g = mainPanel.getGraphics();
    g.drawImage(image, 50, 50, null);

and the stack trace:

null
eter
BufferedImage@6a5f6303: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1c5d9084 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 384 height = 216 #numDataElements 3 dataOff[0] = 2
Exception in thread "main" java.lang.NullPointerException
    at Main.<init>(Main.java:41)
    at Main.main(Main.java:17)
TomLisankie
  • 3,785
  • 7
  • 28
  • 32
  • 1
    Please indicate which line is line 41 of `Main.java`. – ajb Jul 06 '14 at 01:29
  • We need to see your main method. – BitNinja Jul 06 '14 at 01:31
  • I would think it is the graphics 'g' that is null -- the exception doesn't come from the drawImage method, but from your method. Test 'g' for null. – arcy Jul 06 '14 at 01:33
  • `getGraphics` may be returning `null`. If so, see http://stackoverflow.com/questions/18171825/null-pointer-exception-on-getgraphics. – ajb Jul 06 '14 at 01:33
  • Line 41 is the last line in the sample I gave. – TomLisankie Jul 06 '14 at 01:34
  • Thanks. In that case, `g` is null. See my previous comment. – ajb Jul 06 '14 at 01:34
  • Inside the constructor of `Main` class it seems, at `line 41`. What is being used that is `null`? Stop taking the `graphics` reference by calling `getGraphics()` instead override `paintComponent()` of a `JPanel/JComponent` and draw image in that method, by using the `Graphics` object received from `Swing` as cited in this [example](http://stackoverflow.com/a/11372350/1057230) – nIcE cOw Jul 06 '14 at 01:35
  • where's mainPanel definition? – Typo Jul 06 '14 at 01:39
  • where/how is declared `mainPanel` ? – Federico Piazza Jul 06 '14 at 01:42

1 Answers1

-3

I think you need to change "/gameobjects/diaz.jpg" to "gameobjects/diaz.jpg' without the leading '/'. If so it's because of relative resource paths as compared to absolute resource paths. '/' specifies absolute, so it's looking for C:/game... (on windows) rather than /game...

Spencer H
  • 450
  • 1
  • 6
  • 17
  • 2
    That should not be the cause of the problem. If it causes `image` to be `null`, that might cause a `NullPointerException` somewhere inside `drawImage`, **not** on the line that calls `drawImage`. Plus you're making baseless assumptions about the questioner's directory setup and environment. – ajb Jul 06 '14 at 01:52