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.

3
  • For better help sooner, post a proper minimal reproducible example that demonstrates your issue Commented Jun 18, 2020 at 20:39
  • see stackoverflow.com/questions/9806421/… Commented Jun 18, 2020 at 20:40
  • 1
    I wouldn't remove the JLabels 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. Commented Jun 18, 2020 at 20:42

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.