-1

I need to make a JFrame with a round button and with a round image as the button's Icon(Any thing will but a mask would be easier for me).

So far I have searched for these things but I have found a round JButton but with text(Making a round button by Java Examples) instead of an image. I (for the masking) have seen the Masking but don't know how to implement it to the button please help

RikSantra
  • 81
  • 1
  • 10

2 Answers2

0

Change the paintComponent(g) method of the RoundButton class as followed.

protected void paintComponent(Graphics g) {
    g.setClip(new Ellipse2D.Double(0, 0, getWidth(), getHeight()));  // set the area that shall be painted
    g.drawImage(bim, 0, 0, getWidth(), getHeight(), null);    // draw the image, if available
    if (getModel().isArmed()) {      // show a slight gray shading when pressing the button
        g.setColor(new Color(127, 127, 127, 80));   // gray with 80 as alpha
        g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
    }
    super.paintComponent(g);
}

In addition, define a global variable private BufferedImage bim and set it with this method:

public void setButtonImage(BufferedImage pbim) {
    bim = pbim;
    repaint();
}

This should work fine for your needs. Like this you have a round button with text and an image.

The_Programmer
  • 186
  • 3
  • 12
0

Some time ago I wrote an OvalButton class that can handle oval, circular and capsule-like shaped JButtons.

In your case, extend the OvalButton class and override getBackgroundImage() method to return the image you want to set as the background. Then add listeners and text as usually. Only a click on the oval/circular area triggers the action.

Example of a button class for your needs:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageButton extends OvalButton {

    private BufferedImage image;

    public ImageButton() {
        super(); // Default is oval/circle shape.

        setBorderThickness(0); // Oval buttons have some border by default.

        try {
            image = ImageIO.read(new File("your_image.jpg")); // Replace with the path to your image.
        } 
        catch (IOException e) {
            e.printStackTrace();
            image = null;
        }
    }

    @Override
    protected BufferedImage getBackgroundImage() {
        return image;
    }
}
Luka Kralj
  • 446
  • 3
  • 12