Java Applet AWT-EventQueue-1 ArrayIndexOutOfBoundsException

时间:2015-11-25 20:25:10

标签: java applet awt-eventqueue

我创建了一个名为lines的Vector,它存储绘制线的终点的坐标点。它通过从存储的坐标中绘制线来完成我想要的任务,但产生以下异常:

Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10
    at java.util.Vector.get(Vector.java:748)
    at DrawPad.paint(DrawPad.java:149)
    at java.awt.Container.update(Container.java:1995)
    at sun.awt.RepaintArea.updateComponent(RepaintArea.java:255)
    at sun.awt.RepaintArea.paint(RepaintArea.java:232)
    at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:358)
    at java.awt.Component.dispatchEventImpl(Component.java:4967)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

2 个答案:

答案 0 :(得分:0)

你的问题很可能在这里:

for(int i = 0; i < lines.capacity(); i += 4)
            g.drawLine(lines.get(i), lines.get(i + 1), lines.get(i + 2), lines.get(i + 3));

你在for循环的每次迭代中将i递增4。这意味着您正在访问Vector Vector的0,1,2和3元素的第一个循环。您正在访问4,5,6,7的下一个循环。接下来您将访问8,9,10,11。行Vector可能没有那么多元素。

答案 1 :(得分:0)

在调用lines.get(i)之前,您需要检查元素是否存在。另外,使用lines.size()而不是lines.capacity()。

for(int i = 0; i < lines.size(); i += 4)
{
    if((i+3) < lines.size())
    {
        g.drawLine(lines.get(i), lines.get(i + 1), lines.get(i + 2), lines.get(i + 3));
    }
}