Retrieve the path of an ImageIcon

前端 未结 2 1803
广开言路
广开言路 2021-01-14 05:22

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 debu

相关标签:
2条回答
  • 2021-01-14 06:16

    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.

    0 讨论(0)
  • 2021-01-14 06:16

    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.

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