Reputation: 11592
Is it possible to be notified of key events on an application level and not on a Component level? What i mean by application level is not having a swing component receive key events but to have a special class listen to system wide key events.
This could be used in an app with no GUI for instance or when a more global handling of key events is needed.
Upvotes: 1
Views: 2590
Reputation: 5980
You can add a global event listener to you application using the addAWTEventListener() method in java.awt.Toolkit.
Of course this will only work when your application has focus.
So for key events you could use:
public class MyGlobalKeyListener implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
// do something here
}
}
// Then on startup register.
AWTEventListener myGlobalKeyListener = new MyGlobalKeyListener();
Toolkey.getDefaultToolkit().addAWTEventListener(myGlobalKeyListener, AWTEvent.KEY_EVENT_MASK);
Upvotes: 2
Reputation: 41142
Not sure if it is possible in native Java: in Windows, you have to create a DLL to hook key events at the system (global) level, I suppose it is a different mechanism in Unix or MacOS, so you have to interface to low level system API to get this done.
Upvotes: 0
Reputation: 1222
Signals are not a universal concept, but certain signals like ctrl+c for shutdown are widespread if not used everywhere. That particular signal can be listened to using a shutdown hook. Calling Runtime.addShutdownHook(Thread) will allow you to know when the VM is being closed for whatever reason and do something on that event.
Upvotes: -1