简体   繁体   English

如何保留ImageIcon的文件名以供以后参考?

[英]How can I retain an ImageIcon's file name for later reference?

Given this code, 有了这段代码,

tableButton = new JButton(new ImageIcon("80F_FG2015.GIF"));

how would I get that String to be returned to me so I can compare it to another String ? 我如何将那个String返回给我,以便可以将其与另一个String进行比较?

Well one way to solve your problem is creating 解决问题的一种方法是创建

tableButton = new JButton(new ImageIcon("80F_FG2015.GIF", "80F_FG2015.GIF"));

The second argument is the description. 第二个参数是描述。 And ImageIcon.toString() method returns the description. 然后ImageIcon.toString()方法返回描述。 So you can very well compare this description with the description from another image icon 因此,您可以很好地将此说明与另一个图像图标的说明进行比较

You can get back the description as follows: 您可以按以下方式获取描述:

System.out.println(((ImageIcon)tableButton.getIcon()).getDescription()); 
//or
System.out.println(((ImageIcon)tableButton.getIcon()).toString());

You can achieve that using Reflection : 您可以使用Reflection实现:

    ImageIcon icon = new ImageIcon(pathImg);
    JButton jButton1 = new JButton(icon);
    Field field = null;
    try {
        Class<? extends ImageIcon> clazz = ((ImageIcon) jButton1.getIcon()).getClass();
        //Get the field "filename" where the Image path is stored. 
        field = clazz.getDeclaredField("filename");
        field.setAccessible(true);
        String path = (String) field.get(icon);
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(AAMainWindow.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(AAMainWindow.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(AAMainWindow.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(AAMainWindow.class.getName()).log(Level.SEVERE, null, ex);
    }

You could create a new class that extends JButton. 您可以创建一个扩展JButton的新类。 Store the string in the class. 将字符串存储在类中。

class MyButton extends JButton
{
    private String filename;

    public MyButton(String filename)
    {
        super(new ImageIcon(filename));
        this.filename = filename;
    }

    public String getFilename()
    {
        return filename;
    }
}

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

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