Rounded Swing JButton using Java

José Leal picture José Leal · Jan 8, 2009 · Viewed 87.1k times · Source

Well, I have an image that I would like to put as a background to a button (or something clicable). The problem is that this image is round, so I need to show this image, without any borders, etc.

The JComponent that holds this button has a custom background, so the button really needs to only show the image.

After searching Google, I couldn't manage to do so. I have tried all the following, but with no luck:

button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setOpaque(true);

And after I paint the icon at the background, the button paints it, but holds an ugly gray background with borders, etc. I have also tried to use a JLabel and a JButton. And to paint an ImageIcon at it, but if the user resizes or minimizes the window, the icons disappear!

How can I fix this?

I just need to paint and round an image to a JComponent and listen for clicks at it...

Answer

Lalchand picture Lalchand · Sep 3, 2010

Create a new Jbutton:

    JButton addBtn = new JButton("+");
    addBtn.setBounds(x_pos, y_pos, 30, 25);
    addBtn.setBorder(new RoundedBorder(10)); //10 is the radius
    addBtn.setForeground(Color.BLUE);

while setting the border for a JButton, call the overridden javax.swing.border.Border class.

addBtn.setBorder(new RoundedBorder(10));

Here is the class

private static class RoundedBorder implements Border {

    private int radius;


    RoundedBorder(int radius) {
        this.radius = radius;
    }


    public Insets getBorderInsets(Component c) {
        return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
    }


    public boolean isBorderOpaque() {
        return true;
    }


    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        g.drawRoundRect(x, y, width-1, height-1, radius, radius);
    }
}