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.
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.