Andrew
Andrew

Reputation: 13863

Retrieve the path of an ImageIcon

Is it possible to get the location of the file that an ImageIcon was created from?

Internally ImageIcon has a transient private URL of its location, which when debugging will show its path, but I can't figure out how to access it. Any suggestions?

Here's what I mean,

public String getPath(ImageIcon icon){
    return ????;
}

Upvotes: 3

Views: 5129

Answers (2)

Charles Goodwin
Charles Goodwin

Reputation: 6652

Have you tried getDescription()?

I only say so because in the documentation for public ImageIcon(String filename) it lists getDescription() under "See Also".

Note: see Jeffrey's comment.

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 44808

You can use reflection to access the private field, but if the ImageIcon wasn't created with a URL the field will be null. If you are creating the ImageIcons yourself you could keep track of the URLs in a map.

ImageIcon icon = ...
Class<? extends ImageIcon> clazz = icon.getClass();
Field urlField = clazz.getDeclaredField("location");
urlField.setAccessible(true);

URL location = (URL) urlField.get(icon);

It is also worth considering that the field name may change in future versions, which may produce exceptions.

Upvotes: 4

Related Questions