title: How to use Key Bindings instead of Key Listeners
body: <p>I'm using <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/event/KeyListener.html" rel="noreferrer"><code>KeyListener</code></a>s in my code (game or otherwise) as the way for my on-screen objects to react to user key input. Here is my code:</p>
  
  <pre><code>public class MyGame extends JFrame {
  
      static int up = KeyEvent.VK_UP;
      static int right = KeyEvent.VK_RIGHT;
      static int down = KeyEvent.VK_DOWN;
      static int left = KeyEvent.VK_LEFT;
      static int fire = KeyEvent.VK_Q;
  
      public MyGame() {
  
  //      Do all the layout management and what not...
          JLabel obj1 = new JLabel();
          JLabel obj2 = new JLabel();
          obj1.addKeyListener(new MyKeyListener());
          obj2.addKeyListener(new MyKeyListener());
          add(obj1);
          add(obj2);
  //      Do other GUI things...
      }
  
      static void move(int direction, Object source) {
  
          // do something
      }
  
      static void fire(Object source) {
  
          // do something
      }
  
      static void rebindKey(int newKey, String oldKey) {
  
  //      Depends on your GUI implementation.
  //      Detecting the new key by a KeyListener is the way to go this time.
          if (oldKey.equals("up"))
              up = newKey;
          if (oldKey.equals("down"))
              down = newKey;
  //      ...
      }
  
      public static void main(String[] args) {
  
          new MyGame();
      }
  
      private static class MyKeyListener extends KeyAdapter {
  
          @Override
          public void keyPressed(KeyEvent e) {
  
              Object source = e.getSource();
              int action = e.getExtendedKeyCode();
  
  /* Will not work if you want to allow rebinding keys since case variables must be constants.
              switch (action) {
                  case up:
                      move(1, source);
                  case right:
                      move(2, source);
                  case down:
                      move(3, source);
                  case left:
                      move(4, source);
                  case fire:
                      fire(source);
                  ...
              }
  */
              if (action == up)
                  move(1, source);
              else if (action == right)
                  move(2, source);
              else if (action == down)
                  move(3, source);
              else if (action == left)
                  move(4, source);
              else if (action == fire)
                  fire(source);
          }
      }
  }
  </code></pre>
  
  <p>I have problems with the responsiveness:</p>
  
  <ul>
  <li>I need to click on the object for it to work.</li>
  <li>The response I get for pressing one of the keys is not how I wanted it to work - too responsive or too unresponsive.</li>
  </ul>
  
  <p>Why does this happen and how do I fix this?</p>