代码之家  ›  专栏  ›  技术社区  ›  Spoike Otávio Décio

JList随机抛出数组索引boundsExceptions

  •  3
  • Spoike Otávio Décio  · 技术社区  · 14 年前

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

    有人知道怎么解决这个问题吗?

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

    3 回复  |  直到 14 年前
        1
  •  8
  •   Spoike Otávio Décio    14 年前

    回转组件是 有时会抛出异常。JList特别会抛出 ArrayIndexOutOfBounds exceptions 清除和添加元素时。

    解决方法是使用 invokeLater method

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

    当然你不需要使用 因为你可以实现一个 可运行的 而是这样:

    // 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);
            }
        }
    });
    
        2
  •  3
  •   iny    14 年前

    它不是线程安全的,因为它要求与内容分开的大小。

        3
  •  0
  •   Tom Hawtin - tackline    14 年前

    你可能是从另一个线程修改它?可能是在执行 JList (或相关的)希望内容保持相同大小的方法。