我正在做某种类型的arkanoid,我被卡住了。我这样做的方式是通过JFrame,JPanel和Timer。所以每次定时器更新都是如此 这个
public class Controller implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
ball.move();
desk.move();
deskCollision();
squareCollision();
repaint();
}
}
我创建了正方形的Arraylist,然后我打印了它们。当我检查与方块和球的碰撞时,它可以工作。所以现在我想删除一个特定的方块,当一个球击中它并改变一个球的方向。首先,我尝试了没有任何循环,就像这样。
if(ListOfSquares.get(24).getBounds2D().intersects(ball.getBounds2D())){
ball.dy = 1;
ball.dx = -1;
ListOfSquares.remove(24);
}
这也有效。但是因为我想制作一个循环,它将通过所有的方块并且总是移除特定的方块,我迷失了。我这样做了,但是 它最终会出现一个错误 - 线程异常" AWT-EventQueue-0" java.util.ConcurrentModificationException -
for(Square square : ListOfSquares){
int index = ListOfSquares.indexOf(square);
if (ball.getBounds2D().intersects(square.getBounds2D())) {
if(ball.dx == -1 && ball.dy == -1){
ball.dy = 1;
ball.dx = -1;
ListOfSquares.remove(index);
}
//etc...
}
}
感谢您的帮助。
答案 0 :(得分:1)
Iterator可以帮助你:
Iterator<String> iter = ListOfSquares.iterator();
while (iter.hasNext()) {
Square squ = iter.next();
if (someCondition)
iter.remove();
}