Why isn't setIcon displaying image on JButton?

落花浮王杯 提交于 2020-01-15 06:42:48

问题


I swear I've looked everywhere and have been googling for hours. I have added actionListeners to all buttons, and when one is clicked, I want to give it an image with setIcon( image ) like so:

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button) {

    ImageIcon icon = new ImageIcon(getClass().getResource("/Images/" +letter+ ".PNG"));
    button.setIcon(icon );
}

1) I know it's retrieving the image because button.getIcon() gives me something like file:/Users/path/to/Images/X.PNG. I've checked if it's null before and after I've set the icon and it's not null afterward.

2) I've tried other variations of setIcon besides getClass()... and ImageIO.read... and BufferedImage.

3) I don't want to add more code because I'm not even sure what else is relevant. I was hoping for some of your speculations

4) In eclipse, I changed my output folder to src (instead of bin), and that's where my Images folder is.


回答1:


I had a the same problem, I think. I was using Eclipse, tested my code in JGrasp and it worked. Turns out Eclipse wants the resources in the Project folder, not the SRC or BIN.



来源:https://stackoverflow.com/questions/17535901/why-isnt-seticon-displaying-image-on-jbutton

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