JList随机抛出ArrayIndexOutOfBoundsExceptions

Spo*_*ike 3 java swing

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

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 8
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这一问题?

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

Spo*_*ike 8

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

解决这个问题以及在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);
Run Code Online (Sandbox Code Playgroud)

当然你不需要使用a,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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)