1

请帮忙解决java.lang.ArrayIndexOutOfBoundsException

我非常随机地得到这个异常,最糟糕的是我无法重现异常。Stack-Trace 显示addTab()抛出该异常。

这是代码-

public class ClosableTabbedPane extends JTabbedPane{

    public void addTab(String title, Component component) {
            super.addTab(title+"       ", component);
        }


    public String getTabTitleAt(int index) {
        return super.getTitleAt(index).trim();
    }

    public void removeTab(int index){
            this.removeTabAt(index);
        }

这是堆栈跟踪-

21 May 2013 09:38:11,992  ERROR eError : java.lang.ArrayIndexOutOfBoundsException: -1
       at java.util.ArrayList.elementData(ArrayList.java:371)
       at java.util.ArrayList.get(ArrayList.java:384)
       at javax.swing.JTabbedPane.getTitleAt(JTabbedPane.java:1112)

at javax.swing.plaf.basic.BasicTabbedPaneUI$Handler.updateHtmlViews(BasicTabbedPaneUI.java:3578)
       at javax.swing.plaf.basic.BasicTabbedPaneUI$Handler.componentAdded(BasicTabbedPaneUI.java:3713)
   at java.awt.Container.processContainerEvent(Container.java:2255)
       at java.awt.Container.processEvent(Container.java:2226)
       at java.awt.Component.dispatchEventImpl(Component.java:4861)

 at java.awt.Container.dispatchEventImpl(Container.java:2287)
       at java.awt.Component.dispatchEvent(Component.java:4687)
       at java.awt.Container.addImpl(Container.java:1131)
       at javax.swing.JTabbedPane.insertTab(JTabbedPane.java:724)

   at javax.swing.JTabbedPane.addTab(JTabbedPane.java:798)
       at net.abc.f.c.b.addTab(Unknown Source)
       at net.abc.f.a.c.a(Unknown Source)
       at com.xyz.b.b.f.<init>(Unknown Source)
       at com.xyz.b.b.f.<init>(Unknown Source)
       at com.xyz.main.c.w.a(Unknown Source)
        at com.xyz.main.c.o.run(Unknown Source)
       at java.lang.Thread.run(Thread.java:722)
-1 Error: java.lang.ArrayIndexOutOfBoundsException: -1
4

1 回答 1

2

因为您以某种方式传递 index-1以从中获取元素ArrayList,并且 index-1是无效索引。索引中的索引ArrayList基于 0 的,如果在传递的索引处没有存储元素,get(index)则会抛出。IndexOutOfBoundException

调用. _ _ _ _ 就像是,get(index)ArrayList

public String getTitleAt(index) {
  if(index >=0 && index<list.size()) {  
     list.get(index);
  }
  return null; //fallback
}
于 2013-05-21T05:43:29.797 回答