Thanks for your answer. I'm not sure if I really understand it correctly. I will
have a try:
For simplicity, assume that the user does not press several keys at once.
This is your code plus some comments from me:
private int currentKeyCode = -1;
public void keyPressed(KeyEvent event)
{
// I believe that this condition always evaluates to true because:
// 1. It evaulates to true the first time this method is called.
// 2. Before the next keyPressed event is sent, we will receive a
// keyReleased event and this will set currentKeyCode = -1
// (see below)
if(currentKeyCode == -1)
{
if(isKeyOfInterest(event.getKeyCode()))
{
currentKeyCode = event.getKeyCode();
//record key value
}
}
}
public void keyReleased(KeyEvent event)
{
// Same here, since:
// 1. this is true the first time keyReleased is called
// 2. If we receive a keyReleased, there must have been a corresponding
keyPressed and this will have set currentKeyCode = e.getKeyCode()
(see above)
if(event.getKeyCode() == currentKeyCode)
{
currentKeyCode = -1;
}
}
private boolean isKeyOfInterest(int keyCode)
{
return((keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9) ||
(keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z));
}
I believe that there is no way of locking, because keyPressed and keyReleased
always come in pairs and are always alternating. When the keyChar of keyPressed
differs from that of the last keyPressed (or the last keyReleased), you can be
sure that the key was really released, but if it is the same you cannot know
since the user may release the key and press it again after some time. Looking
at the timestamps (getWhen()) will tell you that some time elapsed between the
last keyReleased and the next keyPressed, but how long do you have to wait?
10ms? 100ms? Or does strictly > 0ms suffice? Maybe Java guarantees that the
timestamps for keyReleased and keyPressed are equal if they are "soft" events.
Cheers,
Simon