XxDiCaprioxX
XxDiCaprioxX

Reputation: 27

Java enhanced for loop (for each loop) throws Exception

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

private List<JLabel> cardImages = new ArrayList<JLabel>();
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.

Upvotes: 0

Views: 156

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236024

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();

Upvotes: 4

Related Questions