import java.util.*; // We don't actually need to do this.. public class ArrayListExample extends PApplet { //declaring a global variable of type ArrayList ArrayList a; void setup() { size(400,300); colorMode(RGB,255,255,255,100); // Creating an instance of ArrayList and storing it in our global variable a = new ArrayList(); } void draw() { background(0); if (mousePressed) { // Create a new ball Ball newBall = new Ball(width,height,10,mouseX,mouseY); // Add the ball to the ArrayList a.add(newBall); // If we have 100 balls or more, remove the first Ball if (a.size() > 100) { a.remove(0); } } // Iterate through the ArraList and get each Ball for (int i = 0; i < a.size(); i++) { // when something comes out of the arraylist via "get" we have to // remind ourselves what type it is. In this case, it's an instance of "Ball" Ball b = (Ball) a.get(i); b.compute(); b.display(); } } /* We are including our Ball class here instead of in a different tab as when we enter "Java mode" we loose the default imports and can't use normal methods like ellipse() and ellipseMode(). By including it inside the main class we get those back. */ class Ball { // our Class variables. int wWidth; int wHeight; int bSize; int x, y; int xDirection, yDirection; // Constructor. This gets called when we create a "new Ball" Ball(int windowWidth, int windowHeight, int ballSize) { wWidth = windowWidth; wHeight = windowHeight; bSize = ballSize; x = 1; y = 1; xDirection = 1; yDirection = 1; } // This is an Overloaded constructor Ball(int windowWidth, int windowHeight, int ballSize, int xPosition, int yPosition) { this(windowWidth, windowHeight, ballSize); x = xPosition; y = yPosition; } // Our method to determine current position of the ball. void compute() { if (x < wWidth && x > 0) { // Move along x axis x += xDirection; } else { // Change direction, from positive to negative and vice versa xDirection = xDirection * -1; x += xDirection; } if (y < wHeight && y > 0) { y += yDirection; } else { yDirection = yDirection * -1; y += yDirection; } } // This actually displays our ball, it gets called in the main draw function void display() { compute(); // first we run the computation ellipseMode(CENTER); ellipse(x,y,bSize,bSize); } } // Close our Ball class } // Close our PApplet derived class