Design Computation

Interactivity With Processing

The Mouse

Processing has simplified ways of making sketches interactive with the mouse and keyboard.

So far we’ve been using two functions, setup() and draw(), by defining our own code blocks associated with those names. These are special, event-driven functions that Processing calls for us. We never explicitly call setup() or draw(). Processing calls setup() when a sketch is started, and then calls draw() periodically until the sketch is over or until we tell it not to.

There are other event-driven functions that we define the same way, that are linked to the mouse and keyboard.

Hello Mouse!

Mouse coordinates and mouse events…

There are several variables available everywhere in a sketch, provided by Processing, that give us the condition of the mouse:

mouseX current x-coordinate of the mouse cursor
mouseY current y-coordinate of the mouse
pmouseX last x-coordinate of the mouse
pmouseY last y-coordinate of the mouse
mousePressed a boolean, true if a mouse button is pressed
mouseButton equal to LEFT, CENTER, or RIGHT

Mouse Events

MOUSE EVENTS

Define these outside of setup() and draw():


  void mouseClicked(){
  // Code here is executed when a mouse button
  // is pressed and released.
}

void mousePressed(){
  // Code here executed when a mouse button
  // is pressed.
}

void mouseMoved(){
  // Executed when the mouse cursor moves.
}

void mouseDragged(){
  // Executed when the mouse moves while a button
  // is pressed.
}

void mouseReleased(){
  // Executed the moment a mouse button is
  // no longer being pressed, but was pressed.
}

A Simple Mouse Example


boolean drawing = false;

void setup(){
  size( 700, 400 );
  smooth();
  strokeWeight( 5 );
}

void draw(){
  if( !drawing )
    background( 255 );
  
  line( mouseX, mouseY, pmouseX, pmouseY );
}

void mousePressed(){
  drawing = !drawing;
}

Hello Keyboard!

Keyboard variables and events work the same way.

key Contains the value of the key pressed.
keyCode Contains special values for shift, alt, etc. See the Processing reference entry here.
keyPressed A boolean, true when a key is pressed.

Keyboard Events

Special functions defined like setup(), draw(), mousePressed(), etc. Called when these events occur.


void keyPressed(){
  // Code executed when a key is pressed. This
  // includes modifiers like shift, ctrl, etc.
}

void keyTyped(){
  // Behaves like keyPressed() except it excludes
  // modifiers like shift, ctrl, etc.
}

void keyReleased(){
  // You can probably guess...
}

An Example from the Processing Reference


// Run this program to learn how each of 
// these functionsrelate to the others 

// Empty draw() to keep the program running...
void draw() { } 

void keyPressed() {
  println("pressed " + int(key) + " " + keyCode);
}

void keyTyped() {
  println("typed " + int(key) + " " + keyCode);
}

void keyReleased() {
  println("released " + int(key) + " " + keyCode);
}