好的,我搜索了这个错误,发现原因可能是我对 Arraylist 的更新与我的 repaint() 方法有某种冲突。我已经多次更改我的代码试图修复它,但要么我无法编译,要么我最终得到完全相同的错误。我正在创建 Space Invaders 并且游戏运行良好,直到我快速射击(即点击 UP 按钮快速)并且出现此错误:(注意:“索引:x,大小:x”中的 x 并不总是 1它的范围从1到6)
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Board.checkCollisions(Board.java:185)
at Board.actionPerformed(Board.java:172)
at javax.swing.Timer.fireActionPerformed(Timer.java:312)
at javax.swing.Timer$DoPostEvent.run(Timer.java:244)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
这是似乎导致问题的代码部分。
public void actionPerformed(ActionEvent e){
if(enemies.size() == 0){
ingame = false;
}
ArrayList ss = gun.getShots();
for(int i = 0; i < ss.size(); i++){
Shot s = (Shot) ss.get(i);
if(s.isVisible()){
s.move();
}
else{
ss.remove(i);
}
}
for(int i = 0; i < enemies.size(); i++){
Enemy en = (Enemy) enemies.get(i);
if(en.isVisible()){
en.move();
}
else{
enemies.remove(i);
}
}
for(int i = 0; i < bunkers.size(); i++){
Bunker b = (Bunker) bunkers.get(i);
if(b.isVisible() == false){
bunkers.remove(i);
}
}
gun.move();
checkCollisions();
repaint();
}
public void checkCollisions(){
ArrayList ss = gun.getShots();
for(int i = 0; i < ss.size(); i++){
Shot s = (Shot) ss.get(i);
Rectangle r1 = s.getBounds();
//Collision for Enemies
for(int j = 0; j < enemies.size(); j++){
Enemy en = (Enemy) enemies.get(i);
Rectangle r2 = en.getBounds();
if(r1.intersects(r2)){
s.setVisible(false);
en.setVisible(false);
}
}
//Collision for Bunker
for(int j = 0; j < bunkers.size(); j++){
Bunker b = (Bunker) bunkers.get(i);
Rectangle r2 = b.getBounds();
if(r1.intersects(r2)){
s.setVisible(false);
b.setVisible(false);
score++;
}
}
}
}
更具体地说,这些代码行:
checkCollisions();
Enemy en = (Enemy) enemies.get(i);
而有时
checkCollisions();
Bunker b = (Bunker) bunkers.get(i);
还有另一个问题。出于某种原因,当我射击外星人或在掩体射击时,我总是必须射击 ArrayList 中的第一个,因为它也会消失。如果我先射击其他人什么都不会发生,那么子弹就会飞过他们。这不是我最关心的问题,所以我理解您是否不想浪费时间向我解释。提前致谢。