I am writing a program that requires that I have a button with an image on top of it, but so far I have not been able to get it to work. I checked several other posts on this site, including How to add an image to JButton .
My code is:
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 works, an error occurs: Exception in thread "main" java.lang.IllegalArgumentException: input == null! This error occurs on the line:
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
I do not think that this error is due to the fact that the file was not found in the java code, since the My Images folder is located in the src folder (I use Eclipse), as recommended by the link above.
Does anyone have any ideas what might be the problem?
Thanks.
source share