Reputation: 1243
I am making a basic little game in Java and I want to have it so that I can use Hashmaps for binding keys..
e.g.- it would be like HashMap and then I would do: hashmap.add(Keys.up, VK_UP);
but this is where I get to my problem, How do i access the hashmap and choose which keys are pressed when the KeyListener returns a pressed key?
Sorry if this question seems baffling but I'm really confused too..
Upvotes: 1
Views: 296
Reputation: 13713
Since all key types for KeyEvent are of type int use the following hash map :
HashMap<Integer, Boolean> keysState = new HashMap<Integer, Boolean>();
.
.
.
public void keyPressed(KeyEvent e) {
keysState.put(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
keysState.put(e.getKeyCode(), false);
}
and now you can test if a key is pressed by :
if (keysState.get(KeyEvent.VK_UP)) {
// Up key is pressed so do the desired action
}
Upvotes: 1
Reputation: 178491
You insert key and value to the hashmap using map.put(key,value)
and retrieves a value based on a key using map.get(key)
You need to make sure that the class of the keys overrides both hashCode()
and equals()
[For library classes - it already is]
Upvotes: 1