无法将对象添加到ArrayList

时间:2018-02-05 02:11:40

标签: java arraylist

我正在尝试将名为Cell的对象添加到名为ArrayList的{​​{1}}。当我运行我的代码时,我收到此错误:

Cells

这是我的主要课程的代码。

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: 
Index: 0, Size: 0

这是我的手机课

/*
This program replicates the Flipper program that I made in Processing. 
It's a light-out kind of game where the object of the game is to turn all of the cells black.
*/
package flipper;

import java.awt.Color;
import java.awt.Graphics;

import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
  *
* @author 21psuby
 */
public class Flipper {

JFrame frame;
DrawPanel drawPanel;
ArrayList<Cell> Cells = new ArrayList<>();

int screenW = 450;
int screenH = 550;

int squares = 3; //Cells on one side
int totalSquares = squares * squares; //Total cells on the screen

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    new Flipper().drawCell();

    new Flipper().run();
}

private void run() {
    frame = new JFrame();
    drawPanel = new DrawPanel();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
    frame.setVisible(true);
    frame.setSize(screenW, screenH);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
}

class DrawPanel extends JPanel {

    private static final long SerialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g) {
        for (int i = 0; i < totalSquares; i++) {
            Cell cell = Cells.get(i);
            int x = cell.getX();
            int y = cell.getY();
            int side = cell.getSide();
            int curve = cell.getCurve();
            g.drawRoundRect(x, y, side, side, curve, curve);
        }
    }
}

private void drawCell() {
    double x = 0;
    double y = 0;
    double side = screenW / squares;
    for (int i = 0; i < squares; i++) {
        for (int j = 0; j < squares; j++) {
            Cells.add(new Cell(x, y, side));
            x += side;
        }
        y += side;
    }
}

}

我已经查看了其他ArrayList问题并尝试了这些问题,但我无法让它工作。

谢谢, Pranav

1 个答案:

答案 0 :(得分:1)

main功能中,每次拨打drawCell()&amp; run(),您实例化了一个新的Flipper对象。它们是Flipper对象的两个不同实例,我们将它们称为实例A&amp;乙

您调用run()的实例B,它的成员变量Cells是一个空数组,大小为0.因此,当您调用{{1}时,它会抛出IndexOutOfBoundsException }}

您应该为此使用相同的对象实例。请尝试在Cells.get(i)函数中替换以下代码:

main

希望这有帮助,祝你好运!