【发布时间】: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 example 或SSCCE。 -
你真的需要
else分支吗?我不明白它为什么在这里。似乎这在第一次检查后改变了组件的位置。 -
我认为您的程序会按照您的指示进行操作:当它与列表中的第一个矩形而不是相交时,标签将被放置到其原始位置 (
else)所以它永远不能与另一个矩形相交。尝试删除此else并查看它是否有效。 -
那是IQV。多么愚蠢的错误......非常感谢您的帮助!
标签: java swing for-loop arraylist