How do I detect the collison of components?

How do I detect the collision of components, specifically JLabels (or ImageIcons?)? I have tried this:

test1.setLocation(x, y);
test1.setLocation(x1, y1);

if(intersects(test1, test2))

public boolean intersects(JLabel testa, JLabel testb)
    boolean b3 = false;
    if(testa.contains(testb.getX(), testb.getY()))
        b3 = true;
    return b3;

When I run this, it does nothing!

I used to use Rectangle, but it didn't go well with me. I was thinking about an image with a border (using and moving an imageicon, but I don't know how to get the x of an ImageIcon or detect collision. I don't know how to detect collision of a label or increase the location either.

I have searched for collision detection with components/ImageIcons, but nothing has came up. I have also searched for getting the x of ImageIcons.


Try using computeIntersection() method from SwingUtilities. According to the Javadoc for this method:

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.

Here's something that you can do with the above:

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);

Another way, as @Jakub suggested was to use intersects() method of Area. Sample code for that would be something like this:

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

    return areaA.intersects(areaB.getBounds2D());

Need Your Help

Hibernate OneToMany association on other than primary

java spring hibernate jpa orm

I am trying to build one to many relationship between two tables using columns other than primary. I want a join between Asset.assetnum and SoftLink.assetnum. I am using hibernate 4 and it always

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.