Pages

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
      • MainFrame.java

In file "MainFrame.java" 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>(ImageIcon.java:181)
    at net.leolink.project_name.client.MainFrame.<init>(Main.java:15)
    at net.leolink.project_name.client.MainFrame.main(Main.java:27)

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.