5

I want to add an image to a JButton. Background of the button is set to black. I tried to add the image on top of it, but nothing was shown. Background color was black but the image was missing.

Code

public class Test extends JFrame {

    JButton b;
    JPanel p;

    Test() {
        p = new JPanel(new BorderLayout());
        b = new JButton();
        b.setBackground(Color.black);
        ImageIcon img = new ImageIcon("C:\\Users\\Aksi\\Documents\\NetBeansProjects\\test'\\src\\test\\Black_B.ico");
        b.setIcon(img);
       
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 400);
        p.add(b);
        add(p);
       validate();

   }
    public static void main(String args[]) throws IOException {
        Test ob = new Test();
        ob.setVisible(true);
    }
}
Community
  • 1
  • 1
Akshay Kumar
  • 53
  • 1
  • 1
  • 6
  • Please have a look at this answer, [HOW TO ADD IMAGES TO YOUR PROJECT](http://stackoverflow.com/a/9866659/1057230) and this [answer](http://stackoverflow.com/a/11372350/1057230) for more info on how to add images in your Project, instead of using Absolute Paths. There is no need to call `validate()`, if you adding things to your Container before setting it to VISIBLE. – nIcE cOw Aug 20 '12 at 08:59

5 Answers5

5

Two things

  1. The path looks wrong
  2. Java doesn't, natively, support the ico format

Take a look at the path, there is quote mark in the path

C:\\Users\\Aksi\\Documents\\NetBeansProjects\\test'\\src\\test\\Black_B.ico

Just be sure it's suppose to be there or not

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

Please note that you should use some Java supported image format like .gif, .png for instance.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
  • Good catch. For a list of the image types that a JRE claims to support, see [`ImageIO.getReaderFileSuffixes()`](http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#getReaderFileSuffixes%28%29). Note the output ***might*** change according to version or OS, so it is best to check at run-time for user images, and stick to JPG, PNG or GIF for application images. – Andrew Thompson Aug 22 '12 at 14:22
1

It is well documented on Oracle.

http://docs.oracle.com/javase/tutorial/uiswing/components/button.html

HOW TO USE ICONS

Good luck!

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
Tejas jain
  • 742
  • 7
  • 20
1

Try this way:

Create package in your java project like com.icon and add icons in it.

You will set icon's on button this way:

button.setIcon(new ImageIcon(MyFrame.class.getResource("com/icon/Ok.png")));

Just an advice: Use .png instead of .ico.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
0

This is the way I used to add picture with text:

Icon a=new ImageIcon(getClass().getResource("a.png"));
buttonname=new JButton("ButtonTittle",a);
Pang
  • 9,564
  • 146
  • 81
  • 122
Adi King
  • 25
  • 1
  • 9