将标签添加到“javax.swing.JTabbedPane”时,“java.lang.ArrayIndexOutOfBoundsException:-1”

时间:2013-05-21 05:39:18

标签: java swing jtabbedpane indexoutofboundsexception

请帮助解决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

1 个答案:

答案 0 :(得分:2)

因为您以某种方式传递索引-1以从ArrayList获取元素,而索引-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
}