如何检测组件的碰撞?

Cou*_*n22 0 java swing components jlabel collision-detection

如何检测组件的碰撞,特别是JLabel(或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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它什么都不做!

我曾经使用过Rectangle,但它对我来说并不顺利.我正在考虑带边框的图像(使用paint.net)和移动图像,但我不知道如何获取ImageIcon的x或检测碰撞.我不知道如何检测标签的碰撞或增加位置.

我已经使用components/ImageIcons搜索了碰撞检测,但没有出现任何问题.我也搜索过获取ImageIcons的x.

Suj*_*jay 5

尝试使用computeIntersection()SwingUtilities中的方法.根据Javadoc的方法:

方便计算两个矩形的交集而不分配新的矩形.如果两个矩形不相交,则返回的矩形从(0,0)开始,宽度和高度为零.

以上是您可以做的事情:

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);
}
Run Code Online (Sandbox Code Playgroud)

另一种方式,正如@Jakub所建议的那样是使用intersects()Area的方法.该示例代码将是这样的:

public boolean intersects(JLabel testa, JLabel testb){
    Area areaA = new Area(testa.getBounds());
    Area areaB = new Area(testb.getBounds());

    return areaA.intersects(areaB.getBounds2D());
}
Run Code Online (Sandbox Code Playgroud)