Updating caps lock and num lock status
843806Apr 29 2008 — edited Apr 29 2008I need to keep track of the status of the caps lock and num lock keys in a status bar of my frame.
I get the current status with a code like this
Toolkit toolkit = Toolkit.getDefaultToolkit();
numLockState = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
capsLockState = toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
fireChangeEvent();
where fireChangeEvent() updates a label in the status bar. The code is invoked when any of the caps lock and num lock keys are pressed (while the window has the focus) and when the window is activated. This code works while the window has the focus (i.e. the status of the keys if correctly tracked). It does not work correctly when the window is activated.
Specifically the following scenario fails:
- The window has focus and the state of the keys if correctly reported by the code above (say caps lock up, num lock
up);
- The window loses focus, i.e., another (non java) window gains the focus;
- The user presses any of the two keys (say the caps lock key);
- The window regains focus.
When the latter event happens the code above is invoked (as a consequence of the window being activated) but it continues to report the status of the keys at the time the focus was lost by the window (caps lock up, num lock up).
It seems that the toolkit does not automatically updates its internal status if a key is pressed when the java window does not have the focus. If I press the caps lock key (so that it returns to the up state) after the window has regained focus the status is updated and the new state is correctly reported. I need to manually realign the status by pressing the keys to have them correctly reported by the toolkit.
Some ideas on how to have correct key status even after the window looses the focus?
Thanks.