Search code examples
javaimageswingjbuttonimageicon

How to get a nice looking button?


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.


Solution

  • 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!