Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);     frame.add(button); 
like image 943
kevinstueber Avatar asked Jan 26 '11 04:01

kevinstueber


People also ask

How do I change a JButton image?

you can use this code: Icon i=new ImageIcon("image. jpg"); jButton1. setIcon(i);

How do I import an image into a JFrame?

If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image.

Can you add image to JPanel?

To add an image to JPanel, the Java Swing framework provides built-in classes such as ImageIO and ImageIcon that you can use to fetch an image.


2 Answers

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.

like image 163
Rogach Avatar answered Sep 22 '22 14:09

Rogach


@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); 
like image 21
ungalcrys Avatar answered Sep 23 '22 14:09

ungalcrys