java - 将图像添加到 ArrayList 时出现 IndexOutofBounds 异常

标签 java image graphics arraylist

我正在尝试将图像对象(海龟的图片)添加到 ArrayList,并使每个单独的对象出现在屏幕上的其他位置。当我将图像添加到 ArrayList 时,出现 IndexOutofBounds 错误,并且屏幕上只出现一个对象。

我尝试将索引设置为较小的值,但屏幕上只出现一只海龟。

ArrayList<Turtle> list = new ArrayList<Turtle>();

public void update(Graphics g) {
    for(int i=0; i<3; i++){
    Random randomNumber = new Random();
    int r = randomNumber.nextInt(50);
        list.add(i+r, turtle);
        turtle.update(g);
    }
}

我的Turtle类中的方法更新如下:

public void update(Graphics g) {
    // Move the turtle
    if (x < dest_x) {
        x += 1;
    } else if (x > dest_x) {
        x -= 1;
    }

    if (y < dest_y) {
        y += 1;
    } else if (y > dest_y) {
        y -= 1;
    }

    // Draw the turtle
    g.drawImage(image, x, y, 100, 100, null);
}

感谢您提前提供的帮助。如果您需要更多信息来解决此问题,请告诉我。

最佳答案

您对 add 的调用似乎是错误的:

list.add(i+r, turtle);

您正在向索引添加一个随机数,该随机数几乎肯定大于列表的大小。引用自the Javadocs for the add method :

Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

关于java - 将图像添加到 ArrayList 时出现 IndexOutofBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038112/

相关文章:

java - 未指定子协议(protocol)时如何拒绝 WebSocket 连接

java - 如何改进我的质数和算法?

android - 图像以不同于应有的比例呈现 - Android 中的 Phonegap

ios - 检测图像中的边缘

java - 如何结合switch语句和if case?

java - 使用破折号和单引号验证名称字符串

c++ - 在 Vulkan 中加载非二次幂纹理

iphone - 我对 AR 应用程序中指南针和 GPS 功能的理解是否正确?

c# - 如何将报告转换为图像?

python - 如何在 Django 中访问通过表单集上传的图像?