I'm trying to add an object called Cell to an ArrayList called Cells. When I run my code I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException:
Index: 0, Size: 0
Here's my code for my main class.
/*
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;
}
}
}
This is my cell class
/*
* This program
*/
package flipper;
/**
*
* @author 21psuby
*/
public class Cell {
private final double x;
private final double y;
private final double side;
private final int curve = 16;
Cell(double xVal, double yVal, double sideVal) {
x = xVal;
y = yVal;
side = sideVal;
}
public int getX() {
return (int) x;
}
public int getY() {
return (int) y;
}
public int getSide() {
return (int) side;
}
public int getCurve() {
return curve;
}
}
I've looked at other ArrayList questions and tried those, but I couldn't get it to work.
Thanks, Pranav
for (int i = 0; i < totalSquares; i++) {Change tofor (int i = 0; i < Cells.size(); i++) {Much safer