I have a class extending JButton that I am trying to apply a .png image to.
The image is irregular in shape, and is surrounded by transparent pixels. I have overridden the paintComponent() method in the JButton to apply my buffered image to the button. Right now, the image is the only thing being drawn, which is what I want.
However, the button is still detecting events in the rectangle around it. Is there a way to limit detection to only the area containing opaque pixels (or rather to not detect events on the transparent pixels)?
Code for button class is below.
public class DrawButton extends JButton{
private BufferedImage bi;
public DrawButton(BufferedImage bi){
setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
this.bi = bi;
}
@Override
protected void paintComponent(Graphics g){
g.drawImage(bi, 0, 0, null);
g.dispose();
}
}
Well I would suggest using a
MouseAdapter, and overridemouseClicked(..). InmouseClickedcheck if pixel is alpha at point of click if it is do nothing, if not do something.super.paintComponent(..)as first call in overridenpaintComponentmethod, but because, especially with buttons, this will redraw theJButtonbackground callsetContentAreaFilled(false)onJButtoninstance to stop this. You may also wantsetBorderPainted(false)too.Here is a small example I made (adapted from here):
if click on smiley: