# Problem with keyPressed when drawing a square

**URL:** <https://discourse.processing.org/t/problem-with-keypressed-when-drawing-a-square/12389>\
**Category:** Coding Questions\
**Created:** [June 29, 2019, 8:21pm UTC](https://discourse.processing.org/t/problem-with-keypressed-when-drawing-a-square/12389 "2019-06-29T20:21:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![karan26](https://avatars.discourse-cdn.com/v4/letter/k/df788c/32.png) [@karan26](https://discourse.processing.org/u/karan26)\
**Post date:** [June 29, 2019, 8:21pm UTC](https://discourse.processing.org/t/problem-with-keypressed-when-drawing-a-square/12389/1 "2019-06-29T20:21:45Z")

</div>

hiii,i am trying to add a square to the canvas when a key is pressed and i want it to remain on the canvas when the key is released . but it disappears when is released the key .can anybody  
help me??  
here is my code

```auto
int squareSize=6;
final float DIFF_SIZE=1;
final int MIN_COLOUR=1;
final int MAX_COLOUR=10;
final float INIT_RED=100,INIT_GREEN=50,INIT_BLUE=80;
final float FINAL_RED=255,FINAL_GREEN=200,FINAL_BLUE=250;
final float MAX_SIZE=40;
final float X_SPACING =10;
final float Y_SPACING=10;
 float squareX,squareY;
void setup(){
size(600,600);}

void draw()
{
 squareX=mouseX-squareSize/2;
squareY=mouseY-squareSize/2;
  background(255);

 drawRowsOfBlocks();

 }

    
  void drawOneBlock()
  {
    
   
    rect(squareX,squareY,squareSize,squareSize);
    for(int i=MIN_COLOUR; mousePressed && i <=MAX_COLOUR/10; i++)
  { float redValue=INIT_RED+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_RED-INIT_RED);
    float greenValue=INIT_GREEN+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_GREEN-INIT_GREEN);
    float blueValue=INIT_BLUE+(i-MIN_COLOUR)/(MAX_COLOUR-MIN_COLOUR)*(FINAL_BLUE-INIT_BLUE);  
    fill(redValue,greenValue,blueValue);
    rect(squareX,squareY,squareSize,squareSize);
    squareSize+=DIFF_SIZE;
  }
  if (squareSize>MAX_SIZE)
  {
    squareSize=6;}
  }
  
  void drawRowsOfBlocks()
  { drawOneBlock();
  
for (int i=1;keyPressed&& i<=2;i++)
    { drawOneBlock();
    
 float squareY2;
 squareY2=squareY+squareSize+Y_SPACING;
squareY=squareY2;
 }}

```

---

<div class="post-metadata">

**Author:** ![itch](https://avatars.discourse-cdn.com/v4/letter/i/8e8cbc/32.png) [@itch](https://discourse.processing.org/u/itch)\
**Post date:** [June 29, 2019, 10:06pm UTC](https://discourse.processing.org/t/problem-with-keypressed-when-drawing-a-square/12389/2 "2019-06-29T22:06:17Z")

</div>

Hey Karan,

There’s a mouseClicked() function which is called after the mouse has been pressed and released, perhaps this would better serve you here?

Also, please remember to format your code correctly by clicking the \</\> button in the editor, or wrapping the code in back ticks (`). This makes it much easier to read!
