The reason your code is not working is because Java is not 'globally' listening for your key event, but only when the menu has your focus and is shown.
This is also the reason why there is no possibility to write a pure Java keylogger. Java only allows you to capture window-directed messages.
A workaround would be to implement one of these options:
- Use JNI/JNA/whatever native wrapper to access global key hooking
- Use an invisible window, always being on top and not shown in the system tray that captures the events. I would not suggest using this one as it may either not work like a charm or annoys your user.
The top approach is not a hard one but will require you to use native access and therefor your application becomes platform-specific.
Good luck!