5.2.3 Event Handling Functions

Event handlers are special functions in an interactive system that are designed to process user actions. Unlike the draw() function, which gets called automatically and continually no matter what the user does, event handlers only get called when specific events occur. Just like with draw() and setup(), Processing has set aside a list of unique function names to be used as event handlers. We have to define these functions in our programs, but as long as we use the appropriate function name, Processing will call these functions for us whenever the relevant events occur.

The mouseClicked() function

Automatically the mouseClicked() function is called once each time the mouse is clicked (e.g. pressed down and then released). Suppose we wanted to write a Processing program in which the user could move the mouse around and draw a circle anywhere they clicked. The following program would do exactly that.

The only thing strange you might note is the word return in the body of the draw() function. Processing requires the draw() function to be there in order to update its canvas, but in this case, we don’t want the function to do anything. So here, the return is just a Python keyword that says the function body is over, and nothing more needs to be done.

The keyPressed() function

The keyPressed() function is automatically called whenever a key — any key — on the computer’s keyboard is pressed. Let’s say we wanted to write a Processing program where the user could click to draw circles on the screen, but also give them the option to erase everything and start over by hitting the spacebar. The following program would do the trick.

This program is nearly identical to our previous one, except that now we’ve added the keyPressed() function. In that function definition, we just call the background() function to erase the screen and replace it with a new, empty background any time the user hits the spacebar, or indeed, any key on their keyboard. There are ways to determine the exact key pressed, but we’ll leave that for later.