The Coder's Handbook   

Mouse and Keyboard

POLLING

Polling vs. Event Handlers

There are two ways to get input from the user. 

Mouse Polling

mousePressed Stores a boolean value:  true if the mouse is pressed, and false otherwise

mouseButton Stores which button was last pressed.  Can be LEFT, RIGHT, or CENTER.

mouseX Stores an integer value containing the cursor's x position 

mouseY Stores an integer value containing the cursor's y position


Code:

if(mousePressed && mouseButton == LEFT)  // Detects if left mouse is pressed

{

   ellipse(mouseX, mouseY, 50, 50);  // Draws an ellipse at the cursor

}


Note: In the example above, note that we need to check mousePressed.  This is because mouseButton simply stores the last button that was pressed - even if it's been a long time.  It doesn't tell us anything about whether the button is still down or not.

Keyboard Polling

keyPressed Stores a boolean value:  true if any key is pressed, and false otherwise

key Stores which key was last pressed.  Works for letters, numbers, symbols, and space.

keyCode Stores which key was last pressed.  Used for UP, LEFT, DOWN, RIGHT, ALT, SHIFT, and CONTROL


Code:

if(keyPressed && key == 'r' // Detects if the 'r' key is pressed

{

   reload();

}

else if(keyPressed && key == '1'// Detects if the number '1' is pressed

{

   setSpeedOne();

}

else if(keyPressed && keyCode == LEFT)  // Detects if the left key is pressed

{

   moveLeft();

}

else if(keyPressed && keyCode == CTRL && key == 'q') // Detects if control and q are both pressed

{

    quit();

}

EVENT HANDLERS

Warning

These might seem like the easy way to get mouse and keyboard input, but they won't work well for all projects.  Similarly, they can cause problems with the AP Create Task Rubric.   Using an event handler will not be required on any tests, but polling is fair game.

Mouse Events

void mousePressed()


Code:

int clickCounter =  0;

void mousePressed()

{

    clickCounter++;        // Increase by one each click
   println(clickCounter);  // Print the count each click

}  

Keyboard Events

void keyPressed()


Code:

int keyCounter =  0;

void mousePressed()

{

   keyCounter++;         // Increase by one each click
   println(keyCounter);  // Print out the count each click

}  

Looking for more input options?  Check out the official reference.  

RESOURCES