Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

java - Trying to load icon from jar file

I am trying to load icons from a jar file. I have both tried to load it from classes within the jar file as well as classes outside the jar file.

outside of the jarfile - returned a null exception

java.net.URL imageURL = LoadHTMLExample.class.getClassLoader()
    .getResource("icons/mouse.png");

in side of the jar file in the LoadHTMLExample

java.net.URL imageURL = this.getClass().getClassLoader()
    .getResource("icons/mouse.png");

get the same error.

I have also tried variations of "icons", "/icons" "icons/" "/icons/mouse.png" "icons/mouse.png"

nothing seems to work any idea

the icon is in the jar file

jar
 --icons --- {all the images}

 --com.blah.blah
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've always used the system class loader, whose path is relative to the root of the JAR:

URL url = ClassLoader.getSystemClassLoader().getResource("icons/mouse.png");
Icon icon = new ImageIcon(url);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...