I am writing a program that requires I have a button with an image over top of it, however, so far, I have not been able to get it to work. I have checked several other posts on this site, including How do I add an image to a JButton.
My Code:
public class Tester extends JFrame
{
public Tester()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
setTitle("Image Test");
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton();
try
{
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
button.setIcon(new ImageIcon(img));
}
catch (IOException ex) {}
button.setBounds(100,100,100,100);
panel.add(button);
}
public static void main(String[] args)
{
Tester test = new Tester();
test.setVisible(true);
}
}
When this code runs, an error results: Exception in thread "main" java.lang.IllegalArgumentException: input == null! This error occurs at the line:
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
I don't think that this error is due to the file not being found by java code, as my Images folder is in the src folder (I am using Eclipse) as recommended by the above link.
Does anyone have any ideas to what the problem may be?
Thanks.
While using Eclipse, you don't keep your images into src folder instead you create a Source Folder
for this purpose. Please refer to this link regarding how to add images to resource folder in Eclipse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With