0

I am gettting a nullpointer excetion when i run the applet in browser, while its working fine through appletviewer.

 titleicon=new ImageIcon(this.getClass().getClassLoader().getResource("image.jpg"));
 img=new JLabel(titleicon)

File locations: Both .class file and image file are in same folder.

C:\project\game.class
C:\project\image.jpg

I tried differennt variations below, none is working in browser but all are fine with appletviewer:

 titleicon=new ImageIcon(this.getClass().getResource("image.jpg"));
 titleicon=new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));
1
  • 1
    Try: titleicon=new ImageIcon(new URL(getCodeBase(), "image.jpg")); Commented Aug 5, 2014 at 6:21

1 Answer 1

2

With a file location of

C:\project\game.class
C:\project\image.jpg

Class.getResource will never work, as this searches the classpath for the required resources.

The use of getResource assumes that the resources are embedded and are relative to the class path.

Without more details, it's difficult to make an accurate suggestion, but I would suggest that you get the images jared without your application code, this way, it will be easier to find.

If you're not using an IDE capable of Jaring your classes and resources, then you will need to have a look at Packaging Programs in JAR Files

Remember, Class#getResource is capable of doing a relative lookup. If the images are not stored in the same package as the class which is loading them, then you need to use an absolute path instead...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.