0

I;m trying to draw an image of a player that i just took off google images. So far nothing is shown when i run my code as i'm making a game. I get the nullpointer exception saying something is wrong with my imageicon and my paintCOmponent method.

THis is the class which has the errors.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D gc = (Graphics2D) g;
    gc.drawImage(getPlayerImg(),row,column, this);
}
public void draw(Graphics2D g2d){
    g2d.drawImage(getPlayerImg(),row,column, this);
}
public Image getPlayerImg(){
     ImageIcon d = new ImageIcon(this.getClass().getResource("me.jpg"));
     return d.getImage();
}

I also have another class which calls the paintComponent method. I thought this class would be the code for making the image appear since it calls an object from the above class.

public void paintComponent(Graphics g){
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        System.out.println("ok");
        c.draw(g2d);
        System.out.println("painted");
        c.setVisible(true);
    }

None of the println are printed out on the screen. I don't know what to do :(. The first class has to do with making the map and the second class calls the methods from the first class and makes it. I can't show too much though.

tony
  • 13
  • 4
  • but doesn't my variable d contain the image that i want to draw so it's not null? – tony May 03 '17 at 05:46
  • The most likely cause is `getPlayerImg` is returning a `null` value. Instead of the loops you seem to jumping through, use `ImageIO.read` to read the image, it will throw an exception if the image can't be read for some reason, but will also block until the image is fully read - so don't do it from within a paint method – MadProgrammer May 03 '17 at 05:49
  • 1
    Also, don't call `super.paint` from within `paintComponent`, you'll get yourself into a `StackOverflowException` – MadProgrammer May 03 '17 at 05:49
  • I took out the code and just used the ImageIO.read and it returns no error so it must mean it gets the image o.o – tony May 03 '17 at 06:24
  • We'd more context before we'd be able to help you further – MadProgrammer May 03 '17 at 06:26
  • like what? All i know is once i add the paintComponent method my map disappears and will only show after i lose the game – tony May 03 '17 at 06:31
  • A runnable example which demonstrates your problem perhaps – MadProgrammer May 03 '17 at 06:32
  • umm how would i do that? – tony May 03 '17 at 06:34
  • [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – MadProgrammer May 03 '17 at 06:48

0 Answers0