kevinstueber kevinstueber - 4 months ago 76
Java Question

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);


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 ="resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {

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