Trying to load icon from jar file

后端 未结 6 1997
时光说笑
时光说笑 2020-12-10 14:49

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

相关标签:
6条回答
  • 2020-12-10 15:00
    Icon icon = new ImageIcon(ClassLoader.getSystemResource("icons/mouse.png"));
    

    From the JavaDoc of getSystemResource():

    Find a resource of the specified name from the search path used to load classes...

    This will find your icons even in a jar-file.

    0 讨论(0)
  • 2020-12-10 15:07

    final java.net.URL imageURL3 = com.java.html.LoadHTMLExample.class.getResource( "icons/" );

    works for the below directory structure

    myjar.jar | |- ... |- LoadHTMLExample.class |- ... -- icons | - mourse.png

    Thanks for the help everyone

    0 讨论(0)
  • 2020-12-10 15:09

    I think that getResource gets the resource relative to the location of LoadHTMLExample.class. So your jarfile should be structured in the following way:

    myjar.jar
     |
     |- ...
     |- LoadHTMLExample.class
     |- ...
     \-- icons
          |
          \- mourse.png
    

    Also, you might be getting stream through getResourceAsStream than getting the URL.

    0 讨论(0)
  • 2020-12-10 15:11

    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);
    
    0 讨论(0)
  • 2020-12-10 15:11

    Is the jar in question on the classpath of your runtime? I have a jar with PNGs in it, and I can recreate the nulls if I don't include it on the classpath. If the jar is there they go away.

    0 讨论(0)
  • 2020-12-10 15:21

    Skip the class loader, and get the resource as a stream instead. If you don't need the URL you can turn them directly into BufferedImages like so. I've left the stream and exception handling as a further exercise.

    InputStream stream = LoadHTMLExample.class
        .getResourceAsStream( "/icons/mouse.png" );
    BufferedImage image = ImageIO.read( stream );
    

    Questioner needs the URL which brings us back to everyone else's suggestions. The images are definitely in the jar aren't they?

    0 讨论(0)
提交回复
热议问题