循环 异常 java,Java增强的for循环(对于每个循环)抛出异常

I was recommended to use a List list = new ArrayList to collect and later remove a number of unspecific JLabel images from my JPanel

private List cardImages = new ArrayList();

public void addCardImage(BufferedImage img, boolean playerCard) {

JLabel imgLabel = new JLabel();

ImageIcon icon;

icon = new ImageIcon(img);

imgLabel.setIcon(icon);

cardImages.add(imgLabel);

if (playerCard)

pCardPanel.add(imgLabel);

else

dCardPanel.add(imgLabel);

display.pack();

}

private void removeCards() {

for (JLabel imgLabel : cardImages) {

remove(imgLabel);

cardImages.remove(imgLabel);

}

display.pack();

}

This code gives me

Exception in thread "AWT-EventQueue-0"

java.util.ConcurrentModificationException

at java.util.ArrayList$Itr.checkForComodification(Unknown Source)

at java.util.ArrayList$Itr.next(Unknown Source)

In the line

for (JLabel imgLabel : cardImages) {

(I don't know if this matters but the Game is runnable and is running on a thread.)

I copied the code as given to me in the answer and I don't see the problem, any ideas? Thanks in advance.

解决方案

Here's the problem:

for (JLabel imgLabel : cardImages) {

remove(imgLabel);

cardImages.remove(imgLabel); // not allowed!

}

You cannot iterate over the elements from a collection and remove elements from it at the same time, that results in a ConcurrentModificationException. Do this instead:

for (JLabel imgLabel : cardImages) {

remove(imgLabel);

}

cardImages.clear();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值