Click the mouse to draw a rectangle. Hit the space bar to clear the window.

Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 3-5: mousePressed and keyPressed
void setup() {
  size(200,200);
  background(255);
}

void draw() {
 // Nothing happens in draw() in this example!
}

// Whenever a user clicks the mouse the code written inside mousePressed() is executed.
void mousePressed() {
  stroke(0);
  fill(175);
  rectMode(CENTER);
  rect(mouseX,mouseY,16,16);
}

// Whenever a user presses a key the code written inside keyPressed() is executed.
void keyPressed() {
  background(255);
}
  • fabrice

    Hi,

    Open the sketch above in a tab of a browser. Open an other tab and return to sketch. I noticed that when you press a key, nothing happens. You must click in the sketch and it works. Please do you know if it’s possible to avoid that ?
    Thanks.

  • http://www.learningprocessing.com Daniel Shiffman

    Unfortunately, this is just the way applets in web browsers work, they need to be selected in order to have \focus\.

  • iceblaze

    ■Hi,

    Snce nothing happens in draw() in this example, why need \draw() { }\?
    Thanks.

  • iceblaze

    I have a new question.draw() { } move to end of the program, it still working. Why?
    Thanks.

  • http://www.learningprocessing.com Daniel Shiffman

    Generally, you still need to have draw() so that the window updates. The order of the functions, setup(), draw(), mousePressed(), etc. does not matter.