JButton中不透明像素的java事件检测
我有一个扩展了JButton
的类,我正试图应用它。png图像到。
图像形状不规则,周围有透明像素。我已经覆盖了JButton
中的paintComponent()
方法,以将缓冲图像应用于按钮。现在,图像是唯一正在绘制的东西,这就是我想要的
但是,按钮仍在其周围的矩形中检测事件。是否有一种方法将检测限制为仅包含不透明像素的区域(或者说而不是检测透明像素上的事件)
按钮类的代码如下
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();
}
}
# 1 楼答案
我建议使用
MouseAdapter
,并重写mouseClicked(..)
。在mouseClicked
中,检查单击点处的像素是否为alpha,如果为“不做任何事情”,如果为“不做任何事情”super.paintComponent(..)
作为重写的paintComponent
方法中的第一个调用调用,但因为,特别是使用按钮,这将在JButton
实例上重新绘制JButton
后台调用setContentAreaFilled(false)
,以停止此操作。您也可能需要setBorderPainted(false)
李>下面是我举的一个小例子(改编自here):
如果单击“笑脸”: