I've got a KeyListener class called Keyboard which implements KeyListener's methods.
There are 4 states keys can have with it (UP, ISUP, DOWN, ISDOWN) all representing whether they're down, or they just became down.
Before every update to the Keyboard, I'd like to change all of the UPs to ISUPS, and DOWNs to ISDOWNs.
There is an Update method on the Keyboard class, but I don't know when to call it (because the addKeyListener() function seems to be magic and just works without having to call any functions [probably launches a thread])
How do I know when to call the Update method? (right before the Keyboard is about to fire events)
Here's the Keyboard class itself:
package game.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;
enum KeyStatus
{
DOWN, ISDOWN, UP, ISUP
}
public class Keyboard implements KeyListener
{
private Map<Character, KeyStatus> keys;
public Keyboard()
{
keys = new HashMap<Character, KeyStatus>();
for (int i = 0; i < 256; i++)
{
keys.put((char)i, KeyStatus.ISUP);
}
}
public void update() //This should be called after every event loop (how?)
{
for (Map.Entry<Character, KeyStatus> ks: keys.entrySet())
{
if (ks.getValue() == KeyStatus.UP)
keys.put(ks.getKey(), KeyStatus.ISUP);
else if (ks.getValue() == KeyStatus.DOWN)
keys.put(ks.getKey(), KeyStatus.ISDOWN);
}
}
public boolean keyDown(char i)
{
return (keys.get(i) == KeyStatus.DOWN || keys.get(i) == KeyStatus.ISDOWN);
}
public boolean onKeyDown(char i)
{
return (keys.get(i) == KeyStatus.DOWN);
}
public boolean keyUp(char i)
{
return (keys.get(i) == KeyStatus.UP || keys.get(i) == KeyStatus.ISUP);
}
public boolean onKeyUp(char i)
{
return (keys.get(i) == KeyStatus.UP);
}
@Override
public void keyPressed(KeyEvent key)
{
keys.put(key.getKeyChar(), KeyStatus.DOWN);
}
@Override
public void keyReleased(KeyEvent key)
{
keys.put(key.getKeyChar(), KeyStatus.UP);
}
@Override
public void keyTyped(KeyEvent key)
{
}
}
KeyListener. Is this not the right way to do it? (Store the current state of the keys in an array, and when you get a DOWN event, change the key in the array? [to DOWN, then after one loop to ISDOWN])