getResources() for ImageIcon - java
Asked Answered
V

3

5

my very first question:

I've been trying to figure this out for a couple of days, but I got to the point I lost my patience. The following are some code and my project structure.

QUESTION: how can I get getResources() to work in eclipse and after being imported to jar?

Thanks for the help.

public enum Icons {
    XXX("src/resoruces/icons/xyz.png");
    private ImageIcon icon;
    Icons(String path) {
       try {
           // will fail miserably in eclipse and after exporting to jar
           URL imageURL = getClass().getClassLoader().getResource(path);
           icon = new ImageIcon(imageURL);
       } catch (Exception e) {
           // works like a char in eclipse and after creating the jar file
           // with the files in the same directory
           System.out.println("getResoruce() did not work");
           icon = new ImageIcon(path);
       }
   }

Project Structure

Velma answered 31/12, 2012 at 18:12 Comment(0)
A
3

If the png files have been packaged into the JAR in the same locations as they are in the original src directory then

XXX("resources/icons/xyz.png");

should produce the right result.

Autoeroticism answered 31/12, 2012 at 18:25 Comment(0)
D
11

Normally when exporting a JAR file from Eclipse, the contents of src/resources are exported minus the src path name itself. To get the image to load from your JAR you could do:

InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));

One way to know for sure is to check:

jar tvf yourjar.jar
Duster answered 31/12, 2012 at 19:1 Comment(0)
A
3

If the png files have been packaged into the JAR in the same locations as they are in the original src directory then

XXX("resources/icons/xyz.png");

should produce the right result.

Autoeroticism answered 31/12, 2012 at 18:25 Comment(0)
E
1

src directory is not available in classpath

InputStream imageInputStream = getClass().getClassLoader().getResourceAsStream("resources/icons/xyz.png");
byte[] imageData = org.apache.commons.io.IOUtils.toByteArray(in)

ImageIcon imageIcon = new ImageIcon(imageData, "description about image");
Estrella answered 31/12, 2012 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.