Super easy KeyAdapter question

Greetings!

I’m trying to write a KeyAdapter which will set values in a boolean array to true is that key is down, and false when they are up. My code looks like this:

This way, I can worry about when to do with key presses in my main game loop. My question is, what size should I make the array keys? Right now, I guessed at 130, but is that reasonable?

Thanks in advance.

Some keys (e.g. win+menu) have a keycode of 65536.

Use a size of 256 and keep the values in range with bitwise-and.

Like this:

keys[e.getKeyCode()&0xff] = true;

Hey, thanks for the tip. :slight_smile:

If tracking the boolean on/off state of keys is sufficient for the type of game you are writing, you might want to go for a more complete solution.

Obviously it’s more expensive, but as this code will not be a performance bottleneck - who cares. (though if so inclined, you could replace the HashSet with a more performant proprietary IntHashSet implementation)



private HashSet<Integer> keys = new HashSet<Integer>();


// note, HashSet is not Thread-safe, hence the need for synchronization.
public synchronized boolean isKeyDown(int keyCode) {
   return keys.contains(keyCode);
}

...

// some other code


addKeyListener( new KeyAdapter() {
   public synchronized void keyPressed(KeyEvent e)
   {
      keys.add(e.getKeyCode());
   }
         
   public synchronized void keyReleased(KeyEvent e)
   {
      keys.remove(e.getKeyCode());
   }
} );

I usually use an ArrayList of buttonsPressed, because it’s rare you’re pressing more than a few buttons at a time and therefore the adding operation is cheaper.

Indeed. Though I hope you are synchronizing access to the ArrayList? (assuming you are querying it from a Thread other than the EDT)

I’ve actually never bothered with synchronizing it. Probably should have!

Before you pull your hair out: AWT keyboard events are unreliable with multiple keys pressed due to key repeat. It tends to “forget” KeyReleased events, so you will probably have the problem with “sticking” keys :confused:

I actually never have had that problem, even without synchronicity.

I have had that problem as well a few times. Does anyone have any solution for that?