How to reference a local image in java?

孤者浪人 提交于 2020-01-05 13:08:27

问题


jLabel5.setIcon(new javax.swing.ImageIcon("./i/login.png"));

I'm trying to reference that image. The path is correct, and the image actually exists. When I use the full path (I.E. "C:/ blah blah" it works, but this doesn't?

The image folder is in the bin folder.


回答1:


//This will retuns the URL of the image file inside your project
  this.getClass().getResource("/i/login.png");

So, your code will be :

URL imageUrl = this.getClass().getResource("/i/login.png");
jLabel5.setIcon(new javax.swing.ImageIcon(imageUrl));

If the image is outside your current package, start the path with /i/login.png, else, don't need the /.



来源:https://stackoverflow.com/questions/17902161/how-to-reference-a-local-image-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!