简体   繁体   English

检索 ImageIcon 的路径

[英]Retrieve the path of an ImageIcon

Is it possible to get the location of the file that an ImageIcon was created from?是否可以获取从中创建 ImageIcon 的文件的位置?

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. ImageIcon 内部有一个临时私有 URL 其位置,调试时会显示其路径,但我不知道如何访问它。 Any suggestions?有什么建议么?

Here's what I mean,这就是我的意思,

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

You can use reflection to access the private field, but if the ImageIcon wasn't created with a URL the field will be null .您可以使用反射来访问私有字段,但如果ImageIcon不是使用URL创建的,则该字段将为null If you are creating the ImageIcon s yourself you could keep track of the URL s in a map.如果您自己创建ImageIcon ,则可以跟踪URL中的 URL 。

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.还值得考虑的是,字段名称在未来的版本中可能会发生变化,这可能会产生异常。

Have you tried getDescription() ?你试过getDescription()吗?

I only say so because in the documentation for public ImageIcon(String filename) it lists getDescription() under "See Also".我之所以这么说,是因为在public ImageIcon(String filename)的文档中,它在“另见”下列出了getDescription()

Note: see Jeffrey's comment.注意:见杰弗里的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM