Search code examples
javaswingiconsjbuttonembedded-resource

How do I add an image to a JButton


I am trying to add an image to a JButton and I'm not sure what I'm missing. When I run the following code the button looks exactly the same as if I had created it without any image attribute. Water.bmp is in the root of my project folder.

ImageIcon water = new ImageIcon("water.bmp");
    JButton button = new JButton(water);
    frame.add(button);

Solution

  • I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

      JButton button = new JButton();
      try {
        Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
        button.setIcon(new ImageIcon(img));
      } catch (Exception ex) {
        System.out.println(ex);
      }
    

    In this example, it is assumed that image is in src/resources/ folder.