# How to save a previous mouse position

**URL:** <https://discourse.processing.org/t/how-to-save-a-previous-mouse-position/24434>\
**Category:** Coding Questions\
**Created:** [October 8, 2020, 12:47pm UTC](https://discourse.processing.org/t/how-to-save-a-previous-mouse-position/24434 "2020-10-08T12:47:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![moms\_spaghetti](https://avatars.discourse-cdn.com/v4/letter/m/839c29/32.png) [@moms\_spaghetti](https://discourse.processing.org/u/moms_spaghetti)\
**Post date:** [October 8, 2020, 12:47pm UTC](https://discourse.processing.org/t/how-to-save-a-previous-mouse-position/24434/1 "2020-10-08T12:47:25Z")

</div>

Hello  
I am having a problem with trying to connect dots ,everytime I click on a position with my mouse I create a dot and what is supposed to happen is that the dots get connected with a line. For this I need to save the previous x and y positions of my dot to connect it to the next dot.But I dont know how to save the previous position. Could anybody help me ?

\</\>

```
int dotX=-10;
int dotY=-10;
int prevDotX;
int prevDotY;
//Executed ONCE, at startup. Setup window size, framerate, etc.:
void setup()
{
size(500,500);
background(0);
}

//Execution LOOP (60 times per second by default):  
void draw()  
{

}  
void drawDot(int size)  
{  
strokeWeight(size);  
stroke(0,255,0);  
point(dotX,dotY);  
strokeWeight(5);  
line(prevDotX,prevDotY,dotX,dotY);

}

//Executed ONLY (but each time) mouse is pressed:  
void mousePressed()  
{  
dotX=mouseX;  
dotY=mouseY;  
drawDot(10);

}

//Executed ONLY (but each time) a key is pressed:  
void keyPressed()  
{

}
```

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [October 8, 2020, 12:58pm UTC](https://discourse.processing.org/t/how-to-save-a-previous-mouse-position/24434/2 "2020-10-08T12:58:43Z")

</div>

use an ArrayList

**How To**

Here is an arraylist, you want this before setup()

`ArrayList<PVector> listMousePositions = new ArrayList<PVector>();`

To add to the arraylist (this could be in the function `mousePressed()`):

`listMousePositions .add(new PVector(mouseX,mouseY));`

**Read value**

`PVector pv = listMousePositions.get(2);`

**display all:**

```auto
for(PVector pv : listMousePositions ) {

   point (pv.x,pv.y); 

}

```

**OR**

```auto
for(int i=0; i<listMousePositions.size()-2; ++) {
      PVector pv1 = listMousePositions.get(i); 
      PVector pv2 = listMousePositions.get(i+1); 
      line (pv1.x,pv1.y,
             pv2.x,pv2.y ); 
}

```

**Set value**

`listMousePositions.set(int, new PVector(mouseX,mouseY));`

(text from the forum)

Chrisir
