Key events (how to stop keyPressed() repeating)

Help please. In the following code I want to change the value of varH and so the color of the letter H once and only once. So, when the H or h key is pressed the value of varH should increase by 1. If the key is kept pressed down the value of varH should not keep increasing.

If the key is released and then pressed again, the value of varH should increase (just) once again.

If this is an operating system problem, is there a work-around?

boolean changeH = true;
int varH = 204;

void setup() {
  size(100, 100);
  noStroke();
  colorMode(HSB, 360, 360, 360);
} 

void draw() {
  background(260);
  if (changeH == true) { 
    fill(varH, 360, 360);
  }
  rect(35, 40, 30, 20);
  rect(15, 15, 20, 70);
  rect(65, 15, 20, 70);
}

void keyPressed() {
  if ((key == 'H') || (key == 'h')) {
    changeH = true;
    varH = varH + 1;
    println(varH);
  }
}

void keyReleased() {
  changeH = false;
}
1 Like

This is what the reference states about how keyPressed() works:
" Because of how operating systems handle key repeats, holding down a key may cause multiple calls to keyPressed() ."

So you might have to work around this problem by manually keeping track, if your key was released inbetween differen key-events.

Here is an example, as a starting point:

int varH = 204;
boolean keyIsReleased = true;

void setup() {
  size(100, 100);
  noStroke();
  colorMode(HSB, 360, 360, 360);
}

void draw() {
  background(260);
  fill(varH, 360, 360);
  rect(35, 40, 30, 20);
  rect(15, 15, 20, 70);
  rect(65, 15, 20, 70);
}

void keyPressed() {
  if (keyIsReleased) {
    if ((key == 'H') || (key == 'h')) {
      varH = varH + 1;
    }
    println(varH);
    keyIsReleased = false;
  }
}

void keyReleased() {
  keyIsReleased = true;
}

And you might want to use the “</>”-button when you post code on this forum, so it gets better readable.

1 Like

With the P2D / P3D renderer key repeat is disabled by default. You can change the renderer by adding P2D to the size call in your setup / settings method: size(yourWidth, yourHeight, P2D);

Technical background:

JavaDocs hint(ENABLE_KEY_REPEAT)

hint(ENABLE_KEY_REPEAT) - Auto-repeating key events are discarded by default (works only in P2D/P3D); use this hint to get all the key events (including auto-repeated).
Call hint(DISABLE_KEY_REPEAT) to get events only when the key goes physically up or down.

2 Likes

Wow, that is excellent. Thank you. Though until now I had no idea what a P2D renderer is. Apart from Rendering, is there any other good reference?