为区域定义一个接口,例如:
//represents any clickable area.
public interface IButton{
boolean contains(int x, int y);
}
然后,如果您希望圆形区域可点击,请定义一个类来检查 x,y 坐标是否在某个位置的某个距离内。
public class CircleButton implements IButton{
Point center;
double radius;
public CircleButton(int x, int y, double radius){
this.center = new Point(x,y);
this.radius = radius;
}
//check if x,y coords are within a radius
//from the center of this circle button
public boolean contains(int x, int y){
double dx = x-center.x;
double dy = y-center.y;
return (Math.sqrt(dx*dx+dy*dy) <= radius);
}
}
创建一个 IButton 列表。您将遍历这些以查看用户是否单击了您的某个不可见按钮。
List<IButton> buttons = new List<IButton>();
buttons.add(new CircleButton(100,100,200);
然后,每次有人点击您的框架时,都会使用鼠标点击的位置迭代您的不可见按钮。
public void mouseReleased(MouseEvent e){
for(IButton b : buttons){
if(b.contains(evt.getX(),e.getY()){
//do something depending on what button was clicked.
}
}
}
您可以轻松了解如何定义像这样的不可见矩形按钮,甚至是不规则的多边形形状。您只需要正确实现contains 方法即可。