JList 随机抛出 ArrayIndexOutOfBoundsExceptions [英] JList throws ArrayIndexOutOfBoundsExceptions randomly

查看:24
本文介绍了JList 随机抛出 ArrayIndexOutOfBoundsExceptions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将项目异步添加到 JList,但我经常从另一个线程获取异常,例如:

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?

(我回答了这个问题,因为它一直困扰着我,并且没有明确的搜索引擎友好的方式来查找此信息.)

推荐答案

Swing 组件不是线程安全的,有时可能会抛出异常.特别是 JList 会在清除和添加元素时抛出 ArrayIndexOutOfBounds 异常.

Swing components are NOT thread-safe and may sometimes throw exceptions. JList in particular will throw ArrayIndexOutOfBounds exceptions when clearing and adding elements.

对此的解决方法以及在 Swing 中异步运行事物的首选方法是使用 invokeLater 方法.它确保异步调用在所有其他请求时完成.

The work-around for this, and the preferred way to run things asynchronously in Swing, is to use the invokeLater method. It ensures that the asynchronous call is done when all other requests.

使用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 :

Of course you don't need to use a SwingWorker as you can just implement a Runnable instead like this:

// 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);
        }
    }
});

这篇关于JList 随机抛出 ArrayIndexOutOfBoundsExceptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆