0

I am learning the basics of programming games in Java. For some reason every single time I created a program with an ImageIcon, I would get an error:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at game.Picture.<init>(Picture.java:14)
at game.Main.<init>(Main.java:11)
at game.Main.main(Main.java:7)

After some experimenting, I found out that when I use the default package that eclipse creates, the program works fine. However when I create my own package, the program returns an error.

Below I have two identical programs, the only difference is one uses the default package and one uses my own package called "game"

enter image description here

I included a view of the package explorer in case it's a problem with the location of ship.png

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Steven
  • 833
  • 3
  • 11
  • 18

1 Answers1

2

I think it is in the location, you should use "/raw/ship.png" instead of "raw/ship.png"

try:

   ImageIcon il = new ImageIcon(this.getClass()
                .getResource("/raw/ship.png");

In the current code "raw/ship.png" will be translated by Java to Package_Name/raw/ship.png which in the example below is game/raw/ship.png. Obviously if the code is run from the default package (package_name=""), Package_Name/raw/ship.png becomes /raw/ship.png and it works.

package game;

...

   ImageIcon il = new ImageIcon(this.getClass()
                .getResource("raw/ship.png");
Bruce Martin
  • 10,358
  • 1
  • 27
  • 38