JList throws ArrayIndexOutOfBoundsExceptions randomly

I try to add elements to the JList asynchronously, but regularly get exceptions from another thread, for example:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 8

Does anyone know how to fix this?

(EDIT: I answered this question because it was listening to me, and there is no clear way to search for information in a search engine.)

+3
source share
3 answers

Swing components are not thread safe and can sometimes throw exceptions. JList, in particular, will throw ArrayIndexOutOfBounds exceptions when clearing and adding items.

Swing invokeLater. , , .

SwingWorker ( Runnable):

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void> () {
    @Override
    protected Void doInBackground() throws Exception {
        Collection<Object> objects = doSomethingIntense();
        this.myJList.clear();
        for(Object o : objects) {
            this.myJList.addElement(o);
        }
        return null;
    }
}

// This WILL THROW EXCEPTIONS because a new thread will start and meddle
// with your JList when Swing is still drawing the component
//
// ExecutorService executor = Executors.newSingleThreadExecutor();
// executor.execute(worker);

// The SwingWorker will be executed when Swing is done doing its stuff.
java.awt.EventQueue.invokeLater(worker);

, SwingWorker, Runnable, :

// This is actually a cool one-liner:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        Collection<Object> objects = doSomethingIntense();
        this.myJList.clear();
        for(Object o : objects) {
            this.myJList.addElement(o);
        }
    }
});
+8

. EDT.

, .

+3

, ? , JList ( ), , .

0

Source: https://habr.com/ru/post/1758730/


All Articles