【问题标题】:How do I detect the collison of components?如何检测组件的碰撞?
【发布时间】:2012-09-01 18:38:48
【问题描述】:

如何检测组件的碰撞,特别是 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;
}

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

我曾经使用Rectangle,但它并不适合我。我正在考虑一个带边框的图像(使用paint.net)并移动一个imageicon,但我不知道如何获取ImageIcon 的x 或检测碰撞。我也不知道如何检测标签的碰撞或增加位置。

我已经搜索了组件/ImageIcons 的碰撞检测,但没有任何结果。我还搜索了获取 ImageIcons 的 x。

【问题讨论】:

    标签: java swing components collision-detection jlabel


    【解决方案1】:

    尝试使用 SwingUtilities 中的 computeIntersection() 方法。根据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);
    }
    

    正如@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());
    }
    

    【讨论】:

    • 这似乎是在处理矩形而不是组件。我没有使用矩形。
    • 但是你的组件有矩形?
    • @Coupon22:为了澄清你的疑惑,Component类getBounds()方法以Rectangle对象的形式获取组件的边界,边界指定了这个组件的宽度、高度和相对于其父级的位置。"
    • 那么我的下一个问题是,加载后如何移动组件/更改位置?
    • @Coupon22:那么这将成为您在 stackoverflow 上可能会问的另一个问题 :) 理想情况下,评论不是提问的地方,通常最好为每个问题保留一个主题 :)
    【解决方案2】:

    您可以自己编写它,请记住,如果两个区域重叠,则两个区域相交,而不仅仅是当一个区域包含 x 和 y 坐标(您正在测试)时。

    如果我是你,我会使用Area。它已经有你需要的containsintersects 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多