Search code examples
javaswingjpaneljlabelrepaint

Calling repaint() For JPanels


When I repaint() the panel, where I'm placing my JLabels on, I get errors, but it still works. I tried putting the panel.repaint(); code in a try statement and that didn't help. Anyone else having problems with repaint() for JPanels?

Error message (copied from the comments):

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: No such child: 21 
at java.awt.Container.getComponent(Unknown Source) 
at javax.swing.JComponent.rectangleIsObscured(Unknown Source) 
at javax.swing.JComponent.paint(Unknown Source) 
at javax.swing.JComponent.paintToOffscreen(Unknown Source) 
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source) 
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source) )

Solution

  • Make sure that all modifications to the UI are carried out in the Event Dispatching Thread, this includes adding and removing components from containers.

    As Leon states, using the invokeLater method will ensure that operations are carried on the EDT correctly.