简体   繁体   English

检索ImageIcon的路径

[英]retrieving the path of an ImageIcon

I have a jlabel that has already an icon, and i want to change the icon when i exit the mouse from the label, i tried this code, it shows no syntax error 我有一个已经带有图标的jlabel,我想在从标签退出鼠标时更改图标,我尝试了此代码,它没有语法错误

private void LabelMouseExited(java.awt.event.MouseEvent evt) {                                   

if(Label.getIcon().toString().equals("cyberjayacinema/images/Blue%20E1"))
    {
        Label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cyberjayacinema/images/red E1.PNG")));
    }

else
    {
            Label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cyberjayacinema/images/white E1.PNG")));
    }

but only the else case works, although the imageicon is set to the if case, so i guess the error is with retrieving the path of the icon, i assume the way i wrote my getImageIcon was wrong, I wish someone can help me with this. 但是只有else情况有效,尽管imageicon设置为if情况,所以我猜错误是与检索图标的路径有关,我认为我编写getImageIcon的方式是错误的,希望有人可以帮助我。 thank you 谢谢

If you just put a System.out.println(label.getIcon().toString()) , you will get something like, this 如果您仅放置System.out.println(label.getIcon().toString()) ,您将得到类似的内容

file:/C:/NetBeansProjects/StackOverflow/build/classes/resources/stackoverflow5.png

As you can see, that will not match your case. 如您所见,这与您的情况不符。

You may want to do something like this, to get just the file name 您可能想要执行以下操作,仅获取文件名

String iconfilename = label.getIcon().toString();
String fileName = iconfilename.substring(iconfilename.lastIndexOf("/"  ) + 1);
System.out.println(fileName);

// output
stackoverflow5.png

Then just check against the file name. 然后只需检查文件名即可。

if ("stackoverflow5.png".equals(fileName)) {
    do something
}

This may help you if you are trying to access image from your project folder 如果您尝试从项目文件夹访问图像,这可能会对您有所帮助

 Lable test;
java.net.URL url = ClassLoader.getSystemResource("res/image.png");
test.setIconImage(Toolkit.getDefaultToolkit().getImage(url));

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

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