MousePressed and MouseReleased to create objects

I have a ball class that creates a ball object. I want to created a ball object when the mouse is pressed, if the mouse is pressed and held the ball should follow the mouse(while the mouse is pressed). When the mouse is releases, the ball should stay at the current mouseX and mouseY, and no longer follow the mouse.

When the mouse is pressed again, another ball object is created and does the same as the first object and so on…A new ball object is created every time the mouse is pressed.

I have some code that creates an object, it follows the mouse and it puts on the canvas when I release the mouse. But if I press my mouse again the original ball goes back to the mouse. How do I “disengage” the ball object so i can make more ball objects that doesnt effect the position of the previously placed balls?.

I plan to use ArrayLists to make many objects .

class Ball {
  float xPos, yPos; 


  Ball(float xPos, float yPos) {
    this.xPos= xPos;
    this. yPos= yPos;
  }
  void drawBall() {
    ellipse(xPos, yPos, 50, 50);
    println("X" + xPos + " Y:"+ yPos);
  }
}
Ball ball1;
Ball ball2;
ArrayList<Ball> ballList = new ArrayList<Ball>();

void setup() {
  size(600, 600);
  ball1=new Ball(900, 900);
  ball2=new Ball(900, 900);
}

void draw() {
  
  background(150);
  if (mousePressed ) {
    ball1.xPos= mouseX;
    ball1.yPos=mouseY;
  }

  ball1.drawBall();
}

//Ball ball1;
//Ball ball2;
ArrayList<Ball> ballList = new ArrayList<Ball>();

int currentNo ; 

void setup() {
  size(600, 600);
  Ball ball1=new Ball(900, 900);
  ballList.add(ball1);
}

void draw() {

  background(150);
  if (mousePressed ) {
    ballList.get(currentNo).xPos = mouseX;
    ballList.get(currentNo).yPos = mouseY;
  }

  for (Ball b1 : ballList) { 
    b1.drawBall();
  }//for
}//func

void mousePressed() {
  Ball ball1=new Ball(900, 900);
  ballList.add(ball1);
  currentNo = ballList.size()-1;
}

// =====================================================================

class Ball {
  float xPos, yPos; 

  Ball(float xPos, float yPos) {
    this.xPos= xPos;
    this.yPos= yPos;
  }
  void drawBall() {
    ellipse(xPos, yPos, 50, 50);
    println("X" + xPos + " Y:"+ yPos);
  }
}//class
//
1 Like