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