Processing Starter Article 9

Keyboard Input

Read the key and keyCode variables, respond to key events, and build an interactive sketch controlled by the arrow keys and other key presses.

⏱ 12 min processing keyboard input events interaction keyCode

The key Variable

When a key is pressed, Processing stores the character in the built-in key variable. This is a Java char — a single character:

void keyPressed() {
  println("You pressed: " + key);
}

You can compare key directly to a character literal:

void keyPressed() {
  if (key == 'r' || key == 'R') {
    // reset something
  }
  if (key == ' ') {
    // space bar was pressed
  }
}

Note that key is case-sensitive: pressing Shift+R gives you 'R', not 'r'. Always check both if case doesn’t matter.

The keyPressed Boolean

Like mousePressed, there’s a keyPressed boolean that is true while any key is held down. Use this inside draw() for continuous actions:

float x = 200;
float y = 200;

void draw() {
  background(30);

  if (keyPressed) {
    if (key == 'w' || key == 'W') y -= 3;
    if (key == 's' || key == 'S') y += 3;
    if (key == 'a' || key == 'A') x -= 3;
    if (key == 'd' || key == 'D') x += 3;
  }

  fill(100, 200, 255);
  noStroke();
  ellipse(x, y, 40, 40);
}

Hold WASD to move the circle. The check happens every frame, so the circle moves smoothly as long as the key is held.

Special Keys: keyCode

Letter and punctuation keys are accessible through key. But special keys — arrow keys, function keys, modifier keys — don’t have a printable character. For those, use the keyCode variable.

When key == CODED, it means the pressed key is a special key. Check keyCode in that case:

void keyPressed() {
  if (key == CODED) {
    if (keyCode == UP)    println("Up arrow");
    if (keyCode == DOWN)  println("Down arrow");
    if (keyCode == LEFT)  println("Left arrow");
    if (keyCode == RIGHT) println("Right arrow");
    if (keyCode == SHIFT) println("Shift");
    if (keyCode == CTRL)  println("Control");
    if (keyCode == ALT)   println("Alt");
  }
}

Built-in key code constants:

Constant Key
UP Up arrow
DOWN Down arrow
LEFT Left arrow
RIGHT Right arrow
SHIFT Shift key
CTRL Control key
ALT Alt / Option key
BACKSPACE Backspace
DELETE Delete
ENTER Enter / Return
ESCAPE Escape
TAB Tab
F1F12 Function keys

For keys not listed above (like most letters), keyCode also holds an integer — it just equals the ASCII value of the character, so for most regular input you’ll use key instead.

Event Functions

As with mouse input, Processing provides event functions that fire at specific moments:

void keyPressed() {
  // Fires once when a key is pressed down
}

void keyReleased() {
  // Fires once when a key is released
}

void keyTyped() {
  // Fires for printable characters only (not special keys)
  // Useful for building text input
}

All three live outside setup() and draw():

void setup() { ... }
void draw() { ... }

void keyPressed() {
  // Handle key press
}

void keyReleased() {
  // Handle key release
}

A Keyboard-Controlled Sketch

Here’s a complete sketch where arrow keys move a shape, WASD rotates and scales it, and other keys change its color and visibility:

float x, y;
float angle = 0;
float scaleAmount = 1.0;
color shapeColor;
boolean showGrid = false;

void setup() {
  size(600, 400);
  x = width / 2;
  y = height / 2;
  shapeColor = color(100, 200, 255);
}

void draw() {
  background(25, 25, 35);

  if (showGrid) drawGrid();

  pushMatrix();
    translate(x, y);
    rotate(angle);
    scale(scaleAmount);

    noStroke();
    fill(shapeColor);
    rect(-30, -30, 60, 60, 8);
  popMatrix();

  // Display current values
  fill(200);
  textSize(12);
  text("Position: " + int(x) + ", " + int(y), 10, 20);
  text("Rotation: " + nf(degrees(angle), 0, 1) + "°", 10, 36);
  text("Scale: " + nf(scaleAmount, 0, 2) + "x", 10, 52);
}

void keyPressed() {
  float moveStep = 5;
  float rotateStep = radians(5);
  float scaleStep = 0.1;

  // Arrow keys — move
  if (key == CODED) {
    if (keyCode == UP)    y -= moveStep;
    if (keyCode == DOWN)  y += moveStep;
    if (keyCode == LEFT)  x -= moveStep;
    if (keyCode == RIGHT) x += moveStep;
  }

  // WASD — rotate and scale
  if (key == 'q' || key == 'Q') angle -= rotateStep;
  if (key == 'e' || key == 'E') angle += rotateStep;
  if (key == 'w' || key == 'W') scaleAmount = constrain(scaleAmount + scaleStep, 0.1, 5.0);
  if (key == 's' || key == 'S') scaleAmount = constrain(scaleAmount - scaleStep, 0.1, 5.0);

  // Number keys — change color
  if (key == '1') shapeColor = color(100, 200, 255);  // blue
  if (key == '2') shapeColor = color(255, 100, 100);  // red
  if (key == '3') shapeColor = color(100, 255, 150);  // green
  if (key == '4') shapeColor = color(255, 220, 50);   // yellow

  // Other keys
  if (key == 'g' || key == 'G') showGrid = !showGrid;  // toggle grid
  if (key == 'r' || key == 'R') resetShape();           // reset position
  if (key == ESCAPE) exit();                            // quit
}

void resetShape() {
  x = width / 2;
  y = height / 2;
  angle = 0;
  scaleAmount = 1.0;
}

void drawGrid() {
  stroke(60);
  strokeWeight(1);
  int gridSize = 40;
  for (int i = 0; i <= width; i += gridSize) {
    line(i, 0, i, height);
  }
  for (int j = 0; j <= height; j += gridSize) {
    line(0, j, width, j);
  }
}

New functions used here:

  • nf(value, digits, decimalPlaces) — formats a number as a string with controlled decimal places
  • degrees(radians) — converts radians to degrees for display
  • exit() — closes the sketch programmatically

Toggling Modes with Key Presses

A common interaction pattern is using keys to toggle between sketch states. Here’s a clean approach using a dedicated variable:

int mode = 0;  // 0 = circles, 1 = squares, 2 = triangles

void keyPressed() {
  if (key == '1') mode = 0;
  if (key == '2') mode = 1;
  if (key == '3') mode = 2;
  if (key == TAB) mode = (mode + 1) % 3;  // cycle through modes
}

void draw() {
  background(30);

  if (mode == 0) {
    ellipse(width/2, height/2, 100, 100);
  } else if (mode == 1) {
    rect(width/2 - 50, height/2 - 50, 100, 100);
  } else {
    triangle(width/2, height/2 - 60, width/2 + 60, height/2 + 40, width/2 - 60, height/2 + 40);
  }
}

The (mode + 1) % 3 pattern is a clean way to cycle through a fixed set of values — when mode reaches 2, adding 1 gives 3, and 3 % 3 = 0, wrapping back to the start.

Building Simple Text Input

For capturing text typed by a user, accumulate characters in a String variable:

String typed = "";

void setup() {
  size(500, 200);
  textSize(24);
}

void draw() {
  background(30);
  fill(255);
  text(typed + "|", 20, height / 2);  // "|" acts as a cursor
}

void keyTyped() {
  if (key == BACKSPACE && typed.length() > 0) {
    typed = typed.substring(0, typed.length() - 1);
  } else if (key == ENTER || key == RETURN) {
    println("Submitted: " + typed);
    typed = "";
  } else if (key != CODED) {
    typed += key;
  }
}

keyTyped() only fires for printable characters, so you don’t need to filter out arrow keys or other specials — except BACKSPACE and ENTER, which are printable in Java’s definition. Handle those with explicit checks.

In the final tutorial, you’ll learn how to save your sketches as image files, export animation frames for video, build standalone applications, and share your work with the world.