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);
you can use this code: Icon i=new ImageIcon("image. jpg"); jButton1. setIcon(i);
If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image.
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.
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.
@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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With