0

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.

  • For better help sooner, post a proper [mre] that demonstrates your issue – Frakcool Jun 18 '20 at 20:39
  • see https://stackoverflow.com/questions/9806421/concurrentmodificationexception-when-adding-inside-a-foreach-loop-in-arraylist – Beko Jun 18 '20 at 20:40
  • 1
    I wouldn't remove the `JLabel`s in this particular case, I'd instead remove the icon inside them. (`label.setIcon(null)`) and set it back when you want to update it. Instead of removing the component itself. – Frakcool Jun 18 '20 at 20:42

1 Answers1

4

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();
Óscar López
  • 232,561
  • 37
  • 312
  • 386