【问题标题】:for loop to check intersection through ArrayList of Rectanglesfor 循环通过 Rectangles 的 ArrayList 检查相交
【发布时间】:2017-06-18 08:23:19
【问题描述】:

这是我在 Stack 上的第一个问题,因此任何建议下次如何做得更好将不胜感激 :) 我创建了一个由几个矩形组成的列表。我正在尝试遍历此列表以检查列表中的矩形与我在此矩形上拖动和释放的 JLabbel 之间的交集。这是我的方法:

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

我已将适当的坐标设置为矩形(检查了数百次)。问题是它只检测与列表中第一个矩形的交集......如果我将标签拖动到另一个放置的矩形上,它将不会检测到它。有什么想法吗?

【问题讨论】:

  • 看起来你只是用一个矩形而不是所有矩形来检查它。
  • "....so any advises how to do it better next time would be appreciated..." -- 请考虑创建并发布有效的minimal reproducible exampleSSCCE
  • 你真的需要else 分支吗?我不明白它为什么在这里。似乎这在第一次检查后改变了组件的位置。
  • 我认为您的程序会按照您的指示进行操作:当它与列表中的第一个矩形而不是相交时,标签将被放置到其原始位置 (else)所以它永远不能与另一个矩形相交。尝试删除此else 并查看它是否有效。
  • 那是IQV。多么愚蠢的错误......非常感谢您的帮助!

标签: java swing for-loop arraylist


【解决方案1】:

我认为你需要改变循环如下:

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

【讨论】:

  • @IQV 已经解决了我的问题。我刚刚在一个括号中添加了一个“else”声明,而不是我应该......谢谢你们的快速回复!
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 2017-09-12
  • 2017-12-24
  • 2015-05-21
  • 2012-04-22
  • 2020-03-24
相关资源
最近更新 更多