Name
mousePressed()
Description
The mousePressed() function is called once after every time a mouse button is pressed. The mouseButton variable (see the related reference entry) can be used to determine which button has been pressed.
This function can be called with or without a MouseEvent parameter. When called with the parameter, you get access to additional information about the mouse event, including the exact coordinates, which button was pressed, and any modifier keys (Shift, Ctrl, Alt, Meta) that were held down. For most simple interactions, the global variables (mouseX, mouseY, mouseButton) provide sufficient information.
Mouse and keyboard events only work when a program has draw(). Without draw(), the code is only run once and then stops listening for events.
Examples
// Click within the image to change // the value of the rectangle int value = 0; void draw() { fill(value); rect(25, 25, 50, 50); } void mousePressed() { if (value == 0) { value = 255; } else { value = 0; } }
// Example showing MouseEvent parameter usage // Click with different buttons and modifier keys void setup() { size(200, 200); background(220); } void draw() { fill(0); textAlign(CENTER); text("Click with different buttons", width/2, 20); text("Hold Shift, Ctrl, or Alt", width/2, 35); } void mousePressed(MouseEvent event) { // Get coordinates from event (unaffected by windowRatio) int x = event.getX(); int y = event.getY(); // Get which button was pressed int button = event.getButton(); // Check modifier keys boolean shift = event.isShiftDown(); boolean ctrl = event.isControlDown(); boolean alt = event.isAltDown(); // Set color based on button if (button == LEFT) fill(255, 0, 0); else if (button == RIGHT) fill(0, 255, 0); else if (button == CENTER) fill(0, 0, 255); // Modify based on modifiers if (shift) fill(red(color(255)), green(color(255)), blue(color(255)), 100); // Draw circle ellipse(x, y, alt ? 40 : 20, alt ? 40 : 20); // Print info println("Button: " + button + " at (" + x + "," + y + ")"); println("Modifiers: Shift=" + shift + " Ctrl=" + ctrl + " Alt=" + alt); }
Syntax
mousePressed()
mousePressed(event)
Parameters
event
(MouseEvent)
the MouseEvent
Return
void
Related

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.