0

I want to load an image to an applet but I keep getting a nullpointerexception whenever I run my program. Here is the code I am using to load the image. Please help.

img = getImage(getDocumentBase(), getParameter("questionmark2.jpg"));
g.drawImage(img, 100, 100, this);
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
gooly bug
  • 135
  • 1
  • 6
  • 1
    Could you please add the code for functions `getImage`. `getDocumentBase` and `getParameters`? – CrApHeR May 14 '15 at 01:38
  • Where is the image located? – MadProgrammer May 14 '15 at 01:39
  • 1
    @CrApHeR [`getImage`](http://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html#getImage(java.net.URL)), [`getDocumentBase`](http://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html#getDocumentBase()), [`getParameter`](http://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html#getParameter(java.lang.String)) – MadProgrammer May 14 '15 at 01:40
  • The image is located on my computer. – gooly bug May 14 '15 at 01:56
  • Is the image located at the same directory? – Ivan Ling May 14 '15 at 01:59
  • It is located in the same directory as the .java file. – gooly bug May 14 '15 at 02:00
  • 1
    try putting img = getImage(getDocumentBase(), "questionmark2.jpg"); – Ivan Ling May 14 '15 at 02:01
  • Or use `BufferedImage img = ImageIO.read(getClass().getResource("/class package name/questionmark2.jpg");`, where `class package name` is the class package separated by `/` instead of `.` – MadProgrammer May 14 '15 at 02:24
  • Ivan thanks for your help but I already tried that. Madprogrammer, can you please explain what you mean by class package. – gooly bug May 14 '15 at 03:21
  • Is it really `questionmark2.jpg` as opposed to `QuestionMark2.jpg` or `questionmark2.JPG` etc.? *"It is located in the same directory as the .java file."* The document base refers to the location of the **HTML**, not the class or the `.java` file. Is the image in the same location as the **HTML?** But why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). – Andrew Thompson May 14 '15 at 03:58
  • I found a different way to do it but thanks for your help! And yes my teacher forced me to code an applet. I keep telling him applets are not proper but he is stubborn! – gooly bug May 14 '15 at 23:08
  • Duplicate of [What is a `NullPointerException` and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it?s=1|2.9102) – user207421 Sep 23 '17 at 12:33

0 Answers0