I’m trying to add items to a JList asynchronously but I am regularly getting exceptions from another thread, such as:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 8
Does anyone know how to fix this?
(EDIT: I answered this question because it’s been bugging me and there is no clear search engine friendly way of finding this info.)
Swing components are NOT thread-safe and may sometimes throw exceptions. JList in particular will throw ArrayIndexOutOfBounds exceptions when clearing and adding elements.
The work-around for this, and the preferred way to run things asynchronously in Swing, is to use the
invokeLatermethod. It ensures that the asynchronous call is done when all other requests.Example using
SwingWorker(which implementsRunnable):Of course you don’t need to use a
SwingWorkeras you can just implement aRunnableinstead like this: