Search code examples
javaimageswingiconsjbutton

Java Swing JButton Image Error Debugging


I am trying to add an image to a JButton. I have placed the image which is called Bloop.png into my file directory under my classes folder and have used the following code

public class Control extends JInternalFrame {

    static JPanel    panelButt;
    static JButton   buttBloop;
    static Image     imgBloop;

    public Control() {

          panelButt = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
          buttBloop = new JButton("Bloop");

          setTitle("Control");
          setSize(400, 300);
          setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);


          // CHECK IF FILE EXISTS : this outputs FOUND when run
          File location = new File("classes/Bloop.png");
          if(location.exists()) {
             System.out.println("FOUND");
          } else {
             System.out.println("NOT FOUND");
          }

          try {
             imgBloop = ImageIO.read(getClass().getResource("classes/Bloop.png"));
             buttBloop.setIcon(new ImageIcon(imgBloop));
          } catch(IOException log) {
             System.out.println(log);
          }

          add(panelButt, BorderLayout.NORTH);
          panelButt.add(buttBloop);

    }

}

When I run it however I am getting an error

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!

Why is this? Did I do something wrong?


Solution

  • Your image Bloop.png is indeed at the root of your classpath, so you should refer to it as "/Bloop.png":

    ImageIO.read(getClass().getResource("/Bloop.png"));