检索ImageIcon的路径 [英] Retrieve the path of an ImageIcon

查看:164
本文介绍了检索ImageIcon的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取创建ImageIcon的文件的位置?

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

内部ImageIcon有一个位置的临时私有URL,在调试时会显示它的路径,但我无法弄清楚如何访问它。有什么建议吗?

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?

这就是我的意思,

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


推荐答案

您可以使用反射来访问私有字段,但如果 ImageIcon 未使用 URL 创建,则该字段将为。如果您自己创建 ImageIcon ,则可以在地图中跟踪 URL

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.

这篇关于检索ImageIcon的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆