Register hotkeys in java (processing)

Viewed 74

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;

  //...
 }
} 
2 Answers

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;
}

Cadin's answer is great (+1), the technique is useful especially when making video games that need fast updates.

If you want to code something similar to an application shortcut (e.g. Ctrl + Shift + S to trigger Save As... on Windows, etc.) you could also make sure of the KeyEvent overrides for keyPressed()/keyReleased() (e.g. keyPressed(KeyEvent key), keyReleased(KeyEvent key);).

Here's a basic Windows example:

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

void draw(){
  background(0);
}

void keyReleased(KeyEvent event){
  println("keyCode",event.getKeyCode(),"control",event.isControlDown(), "alt", event.isAltDown(), "shift", event.isShiftDown());
  // Ctrl + Shift + S
  if(event.getKeyCode() == 83 && event.isShiftDown() && event.isControlDown()){
    println("Save As...");
  }
  // Ctrl + Alt + J
  if(event.getKeyCode() == 74 && event.isAltDown() && event.isControlDown()){
    println("Step Out");
  }
}

On OSX shortcut might be slightly different but you can check the platform property first. (e.g. if(platform == MACOSX){...} / if(platform == WINDOWS){...})

Related