2
\$\begingroup\$

This is how I read the keyboard in my game:

    @Override
public void keyPressed(KeyEvent key) {
    keypressed=true;

    if (key.getKeyCode() == KeyEvent.VK_UP) {
        keyup=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_DOWN) {
        keydown=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_ENTER) {
        keyenter=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_ESCAPE) {
        keyesc=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_W) {
        keyw=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_S) {
        keys=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_A) {
        keya=true;
    }  

    if (key.getKeyCode() == KeyEvent.VK_D) {
        keyd=true;
    }  
}

Is there a more efficient, simpler, or neater way to do this?

\$\endgroup\$
  • 3
    \$\begingroup\$ So you've succeeded in setting some variables based on the keys pressed. Then what do you do with all those variables? \$\endgroup\$ – 200_success Apr 15 '14 at 7:42
5
\$\begingroup\$

Yes there is. As KeyEvent is an enumeration type, you can instead use a switch-statement:

char key;
boolean isSpecialKey = false;
SpecialKey specialKeyValue;
switch(key.getKeyCode()){
    case KeyEvent.VK_UP:
       key = '';
       isSpecialkey = true;
       specialKeyValue = SpecialKey.ARROW_UP;
       break;
    case KeyEvent.VK_W:
       key = 'w';
       break;
    //Continue...
}

I took the liberty of creating a new SpecialKey enum that is supposed to handle special keys when pressed. For these, there is also the isSpecialKey flag. You simply wouldn't create a case for Keys that you don't handle. Instead, do nothing in the default case.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.