Adding an Image to JButton

I want to add an image to JButton. Button background set to black. I tried adding an image on top of it, but nothing was shown. The background color was black, but the image was missing.

the 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);
    }
}
+5
source share
5 answers

Two things

  • The way looks wrong
  • Java does not support but supports format ico

Take a look at the way, there is a quote label on the way

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

Just make sure it should be there or not

+5
source

Please note that you must use some image format supported by Java, for example .gif, .png.

+2
source

Try as follows:

Create a package in your java project, for example com.icon, and add icons to it.

You will set the icon on the button as follows:

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

Just a tip: use .png instead of .ico.

+1
source

So I used to add an image with text:

Icon a=new ImageIcon(getClass().getResource("a.png"));
buttonname=new JButton("ButtonTittle",a);
0
source

All Articles