Retrieve the path of an ImageIcon

前端 未结 2 1820
广开言路
广开言路 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 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.

提交回复
热议问题