Akshay Kumar
Akshay Kumar

Reputation: 53

Adding image to JButton

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

Upvotes: 5

Views: 42116

Answers (5)

Adi King
Adi King

Reputation: 25

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

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

Upvotes: 0

Branislav Lazic
Branislav Lazic

Reputation: 14826

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.

Upvotes: 1

Tejas jain
Tejas jain

Reputation: 752

It is well documented on Oracle.

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

HOW TO USE ICONS

Good luck!

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

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

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347332

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

Upvotes: 5

Related Questions