这是我关于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);
}
}
我已设置为矩形适当的坐标(已检查数百次)。问题是它只检测到列表中第一个矩形的交集...如果我将标签拖到另一个放置的矩形上,它将无法检测到它。有什么想法吗?
答案 0 :(得分: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);
}