Search code examples
javaswingnetbeansjbuttonembedded-resource

How to set a image icon to JButton?


I want to set a image icon to JButton, here the code that i tried:

public class Calculator {

    public static JFrame f;

    Calculator() throws IOException{

        JButton b;

        f = new JFrame();
        Image play = ImageIO.read(getClass().getResource("images/play.png"));
        b = new JButton(new ImageIcon(play));

        b.setBounds(250,250,75,20);

        f.add(b);
        f.setSize(500,500);
        f.setLayout(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws IOException {

        new Calculator();
    }
}

The program runs normally without errors, but the image didn't appear.

I think the image url is wrong.

I am using netbeans, so I created a folder named images in the source packages directory.


Solution

  • The issue can be resolved by prefixing the resource path with a slash:

    Image play = ImageIO.read(getClass().getResource("/images/play.png"));
    

    This denotes that the image folder is at the root location of all resources and not relative to the current class location.

    Credits partially go to Andrew Thompson's comment.