Baki1790
Baki1790

Reputation: 11

for loop to check intersection through ArrayList of Rectangles

This is my FIRST question on Stack so any advises how to do it better next time would be appreciated :) I've created a list consist of couple Rectangles. I'm trying to loop through this list to check the intersection between rectangle in a list and my dragged and released JLabbel on this rectangle. Here is my approach:

public void mouseReleased(MouseEvent e) {
    Component comp = (Component) e.getSource();
    Point locOnScreen = e.getLocationOnScreen();
    int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
    int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
    boundsSet(x, y, comp);//method to limit dragging space in contentPane 

    List<Rectangle> placeHolder = new ArrayList<Rectangle>();

    placeHolder.add(leftDesk);
    placeHolder.add(leftPainting);
    placeHolder.add(underBed);
    placeHolder.add(onBed);
    placeHolder.add(centerPainting);
    placeHolder.add(window);
    placeHolder.add(wardrobe);

    for (Rectangle holder : placeHolder) {
        if (holder.intersects(comp.getBounds())) {

            JOptionPane.showMessageDialog(null, "Correct place !");
            GameStatus.points += 10;
            GameStatus.nrOfItems--;
            if (GameStatus.points == 50)
                GameStatus.level++;

        } else
            comp.setLocation(initialLoc);
    }
}

I've set to Rectangles appropriate coordinates(checked hundreds times). The problem is that it detects only intersection with the first Rectangle in a List... If I will drag the label on another placed rectangle it will not detect it. Any ideas?

Upvotes: 0

Views: 314

Answers (1)

Zefick
Zefick

Reputation: 2119

I think you need to change the cycle as follows:

boolean found = false;

for (Rectangle holder : placeHolder) {
    if (holder.intersects(comp.getBounds())) {

        JOptionPane.showMessageDialog(null, "Correct place !");
        GameStatus.points += 10;
        GameStatus.nrOfItems--;
        if (GameStatus.points == 50)
            GameStatus.level++;
        found = true;
        break;
    }
}
if (!found) {
    comp.setLocation(initialLoc);
}

Upvotes: 1

Related Questions