Reputation: 3547
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.
Upvotes: 1
Views: 8795
Reputation: 5146
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.
Upvotes: 1
Reputation: 48258
Try with b.setIcon(new ImageIcon(getClass().getResource("images/play.png")));
Upvotes: 1