keyPressed with multiple keys

Hello,
i am trying to write a program which shows two arrays with numbers and if I press the number of an array element, this element should disappear and the others replace the gap. That’s function, but I wan’t to do something special like: If I press ‘2’ and then ‘d’ and then ‘Enter’ the second element should disappear. I already tried it with multiple if-clings but it didn’t worked. Does someone has an idea?

void keyPressed()                             
{
  position = key;
  println(position);
  position = Character.getNumericValue(key);
println(position);

      if (keyPressed)
      {
        loesche = true;
      }

}
1 Like

Hi,

Each key press triggers keyPressed() event. So if you want to track keys “2”, “d” and enter, you need to store key presses or have a state change.

Here’s a code that prints “Wohoo” only and only if keys 2 and d are pressed in succession. It’s also a simple state machine.

boolean step1 = false;
boolean step2 = false;

void setup() {
  size(400,400);
}

void draw() {
}

void keyPressed() {
  if(key=='d') {
    step1=true;
  } else if(key=='2' && step1==true) {
    step2 = true;
    println("Wohoo");
  } else {
    step1 = false;
    step2 = false;
  }
}
1 Like

Thanks for your fast respond. I implemented your suggestion now into my code, but I have little trouble. In your code you made the key ‘d’ to an one time activation button to become the possibility to println Wohoo if you pressed ‘2’. But I want to make the first key responsive to the numbers 1 to 9. For example if you press number ‘4’ than ‘d’ and than Enter, the 4th element of the array gets deleted.
if(key = elementname[i]) {...} I tried this version but that didn’t help. Than I tried this: if(key >= '1' && key <= '9') now it’s function half. The system now detect all numbers but don’t assign them to the array element with the same number.

Okey, so you’d need to store the numeric value too. Because key presses give characters you’d also need a way to change characters to numbers. As you already found out characters can be used in comparison as they are stored with two bytes and can be treated as numbers. Numbers are ordered as 0,1,2,3,…,9, so if we reduce value of char ‘0’ from a char that is a number we get the same numeric value.


void keyPressed() {
  if(key >= '1' && key <= '9') {
    step1=true;
    value = key - '0';
  }