0

I tried to use a custom image for a JButton, and it works well except for the fact that there is a white box around it. I am not sure how to fix this, and would like some help. (I create the button using new ImageButton("Quit", "src/button.png", 128, 64). The button is not resizable, and the image file is 256X128)

Button Class:

public class ImageButton extends JButton {

    Image image;
    ImageObserver imageObserver;

    public ImageButton(String text, String filename, int width, int height) {
        super(text, new ImageIcon(filename));
        setSize(width, height);
        setHorizontalTextPosition(JButton.CENTER);
        setVerticalTextPosition(JButton.CENTER);
    }
}

Picture using getInsets override:

Picture of the "Quit" button.

Barett
  • 5,826
  • 6
  • 51
  • 55
Octavia Togami
  • 4,186
  • 4
  • 31
  • 49

3 Answers3

1

This is more than likely due to fact that you have non-zero insets in the ImageButton. Try overriding getInsets():

@Override
public Insets getInsets() {
   return new Insets(0, 0, 0, 0);
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    I tested the button but did not see this effect. What layout are you using in the button's container? (I used `FlowLayout`) Consider posting a [sscce](http://sscce.org/). – Reimeus Nov 19 '12 at 02:14
  • I'm using a GridBagLayout in Full-Screen Exclusive Mode, however I am painting the components in the JPanel I have via `j.paintComponents(bg);` with bg being `BufferedImage b = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D bg = b.createGraphics();` – Octavia Togami Nov 19 '12 at 02:21
0

Please use paintComponent() to draw a custom image in place of a default JButton. Also if you're going to paint on a JPanel, then use JPanel.print() the image on to the JPanel.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

Ok, Andrew helped me on this one. He pointed me to this link, and it turns out I just have to disable the border and the content area. Thanks Andrew!

More info if you don't want to follow the link: The main thing you should get out of this is that the border should be null like so: button.setBorderPainted(false); button.setBorder(null); and you should also set the content area to not be drawn: button.setContentAreaFilled(false); That's the main points for making your own custom button!

Community
  • 1
  • 1
Octavia Togami
  • 4,186
  • 4
  • 31
  • 49