How to add a global action event listener? I've tried
Toolkit.getDefaultToolkit ().addAWTEventLis开发者_StackOverflowtener (this, AWTEvent.ACTION_EVENT_MASK);
but it doesn't work.
(example) to listen for all MouseEvents and KeyEvents in a application you can use:
long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK
+ AWTEvent.MOUSE_EVENT_MASK
+ AWTEvent.KEY_EVENT_MASK;
Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener()
{
public void eventDispatched(AWTEvent e)
{
System.out.println(e.getID());
}
}, eventMask);
As this code executes on the Event Dispatch Thread you will need to make sure that it executes quickly to prevent the GUI from becoming unresponsive. The above approach is used here if you want to look at a working example.
See here for more information : Global Event listeners
And this for a thourough study : AWT Event Listener
Globally listening to Action Events does not work for Swing components like JButtons since they directly call their listeners instead of dispatching the event through the AWT event queue. Java bug 6292132 describes this problem.
Unfortunately, I know of no workaround short of registering the listener with every component.
There is Global Event Dispatcher in java swing which you could use. What it basically does is, intercept the event, do your custom logic and dispatch it to the actual component. For example, if you wish to intercept a mouse click event-
EventQueue eventQueue = java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.push(new EventQueue()
{
@Override
public void dispatchEvent(java.awt.AWTEvent awtEvent)
{
if((awtEvent instanceof MouseEvent && awtEvent.getID() == MouseEvent.MOUSE_CLICKED)
{
// do your custom logic here
}
}
super.dispatchEvent(awtEvent);
});
You can find more info on this here - Event Dispatchers
精彩评论