Alex Rivera | Logout

Rounded Swing JButton using Java

Asked 2009-01-08T11:25:30.087
26

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...

Edit
Report

1 Answer

1

I would recommend overriding paint(Graphics g) method as so:

class JImageButton extends JComponent implements MouseListener {
    private BufferedImage img = null;

    public JImageButton(BufferedImage img) {
        this.img = img;
        setMinimumSize(new Dimension(img.getWidth(), img.getHeight()));
        setOpaque(false);
        addMouseListener(this);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }
}
answered 2009-01-08T19:10:43.830

Your Answer