25 Apr 2012

How to export all resources into runnable JAR file in Eclipse?

Well, the post title says it all.
I was stuck in doing that, but today I've found the solution.

For example, I have the directory tree like this:
  • src
    • net.leolink.project_name.resources
      • myicon.png
    • net.leolink.project_name.client

In file "" I want to display "home.png", so I used this code:
ImageIcon icon = new ImageIcon(this.getClass().getResource("../resource/home.png"));
JLabel lb = new JLabel(icon);

Of course, it works well when you compile in Eclipse, but then you export to runnable JAR file (File->Export->Java->Runnable JAR file), and try to run the JAR file with command line you will get the error like:
Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(
    at net.leolink.project_name.client.MainFrame.<init>(
    at net.leolink.project_name.client.MainFrame.main(

So what is the solution?
It's so simple, just change your code to (notice the bold texts):
ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("net/leolink/project_name/resource/home.png"));
JLabel lb = new JLabel(icon); 

Then try to export again, the exported JAR file should work well ;)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.