如何检测组件的碰撞,特别是 JLabels(或 ImageIcons?)?我已经尝试过:
add(test1);
test1.setLocation(x, y);
add(test2);
test1.setLocation(x1, y1);
validate();
if(intersects(test1, test2))
{
ehealth-=50;
}
public boolean intersects(JLabel testa, JLabel testb)
{
boolean b3 = false;
if(testa.contains(testb.getX(), testb.getY()))
{
b3 = true;
}
return b3;
}
当我运行这个时,它什么也没做!
我曾经使用矩形
,但它不适合我。我正在考虑带有边框的图像(使用paint.net)并移动图像图标,但我不知道如何获取图像图标的x或检测碰撞。我也不知道如何检测标签的碰撞或增加位置。
我已经搜索了组件/ImageIcons 的碰撞检测,但没有任何结果。我还搜索过获取 ImageIcons 的 x。
最佳答案
尝试使用 SwingUtilities 中的 computeIntersection()
方法。根据Javadoc对于此方法:
Convenience to calculate the intersection of two rectangles without allocating a new rectangle. If the two rectangles don't intersect, then the returned rectangle begins at (0,0) and has zero width and height.
您可以使用上述内容执行以下操作:
public boolean intersects(JLabel testa, JLabel testb){
Rectangle rectB = testb.getBounds();
Rectangle result = SwingUtilities.computeIntersection(testa.getX(), testa.getY(), testa.getWidth(), testa.getHeight(), rectB);
return (result.getWidth() > 0 && result.getHeight() > 0);
}
另一种方法,正如@Jakub建议的那样,是使用Area的intersects()
方法。示例代码如下所示:
public boolean intersects(JLabel testa, JLabel testb){
Area areaA = new Area(testa.getBounds());
Area areaB = new Area(testb.getBounds());
return areaA.intersects(areaB.getBounds2D());
}
关于java - 如何检测组件的碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12325553/