50

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);
Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
kevinstueber
  • 2,896
  • 3
  • 25
  • 26
  • That **should** work...can you try using the `URL` form of the `ImageIcon` constructor and see what it does? It might be that it can't find the image file for some reason. – Cameron Skinner Jan 26 '11 at 04:39
  • Yes, it's working now. No changes to the code. Thanks everyone for your suggestions. – kevinstueber Jan 28 '11 at 04:38

10 Answers10

78

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.

Oldalf
  • 21
  • 7
Rogach
  • 24,614
  • 20
  • 85
  • 166
  • 3
    I dont know why but this didnt work either for me. I even build a function which searched the wanted files in the directory and found them - still no icons. So, i just use the line: button1.setIcon("path/pic.png"); - this runs. Any ideas why? – Yannic Hansen Oct 24 '14 at 14:59
18

@Rogach

and you may like to add:

// to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);
ungalcrys
  • 4,890
  • 2
  • 36
  • 22
7

It looks like a location problem because that code is perfectly fine for adding the icon.

Since I don't know your folder structure, I suggest adding a simple check:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.

Kamila Szewczyk
  • 1,837
  • 1
  • 15
  • 33
donnyton
  • 5,796
  • 9
  • 41
  • 60
5

You put your image in resources folder and use follow code:

JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));
ParisaN
  • 1,397
  • 2
  • 18
  • 47
3
public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }
prolink007
  • 32,590
  • 23
  • 113
  • 179
KFC
  • 523
  • 1
  • 4
  • 17
  • 6
    Too complex. There is a built-in mechanism for adding icons to buttons, why create additional problems? – Rogach Jan 26 '11 at 04:33
  • @Rogach Not specifically for this question, but in my case it was useful to have further control on where the image was placed in the button. – Aldo Canepa Feb 23 '21 at 18:45
2
buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));
MathieuF
  • 3,100
  • 5
  • 29
  • 34
2

I did only one thing and it worked for me .. check your code is this method there ..

setResizable(false);

if it false make it true and it will work just fine .. I hope it helped ..

Dan
  • 31
  • 1
  • the frame (?) being resizable or not is irrelevant – kleopatra Dec 22 '11 at 16:39
  • Yes you maybe right .. but when you have a Borderlayout and then you make this statement.. you restrict the frame .. thus if you make true it will give your frame the space. – Dan Dec 24 '11 at 15:25
1
//paste required image on C disk
JButton button = new JButton(new ImageIcon("C:water.bmp");
1

This code work for me:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);
CamelTM
  • 1,187
  • 11
  • 16
1

For example if you have image in folder res/image.png you can write:

try
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("image.png");
    // URL input = classLoader.getResource("image.png"); // <-- You can use URL class too.
    BufferedImage image = ImageIO.read(input);

    button.setIcon(new ImageIcon(image));
}
catch(IOException e)
{
    e.printStackTrace();
}

In one line:

try
{
    button.setIcon(new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("image.png"))));
}
catch(IOException e)
{
    e.printStackTrace();
}

If the image is bigger than button then it will not shown.

Oxygenium
  • 61
  • 1
  • 2
  • 7