Why isn't setIcon displaying image on JButton?

2019-07-21 02:42发布

问题:

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.