Search code examples
javaprocessing

Register hotkeys in java (processing)


What is the best way to create an efficient hotkey-registering function in java? I am not really looking forward to using libraries or other add-ons for this because it seems easy to code, but I do care a lot about the efficiency of the code, so please, correct me if it could be better.

Here is my code idea:

Kyeboard my_keyboard;

class Keyboard{
 boolean control, alt, shift;
 boolean a, b, c, d;  // ... x,y,z; here other needed letters can be declared

 Keyboard(){

 }
} 

void setup(){  // This gets executed only once, a built-in function in processing
 my_keyboard=new Keyboard();
}

void keyPressed(){  // Another built in function in processing, detects when a key is pressed
 switch(keyCode){   
  case 18:
  my_keyboard.alt=true;
  break;

  case 17:
  my_keyboard.control=true;
  break;
 
  case 16:
  my_keyboard.shift=true;
  break;

  //...
 }
}

void keyReleased(){  // Again a built-in function
 switch(keyCode){
  case 18:
  my_keyboard.alt=false;
  break;

  case 17:
  my_keyboard.control=false;
  break;

  case 16:
  my_keyboard.shift=false;
  break;

  //...
 }
} 

Solution

  • If you use an array, indexing off of the keycode, you can store down states for every key without having to list them all explicitly in a giant switch case like you have.

    boolean[] keys = new boolean[256];
    
    void keyPressed(){  
      keys[keyCode] = true;
    }
    
    void keyReleased() {
      keys[keyCode] = false;
    }