How to add a global action event listener?

How to add a global action event listener? I tried

Toolkit.getDefaultToolkit ().addAWTEventListener (this, AWTEvent.ACTION_EVENT_MASK); 

but that will not work.

+4
source share
3 answers

Listening to Action Events globally does not work for Swing components such as JButtons, as they directly call their listeners instead of dispatching the event through the AWT event queue. Java Error 6292132 describes this problem.

Unfortunately, I do not know about a workaround that does not register the listener with each component.

+3
source

(example) to listen to all MouseEvents and KeyEvents in an application that 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); 

Since this code runs in Thread Dispatch Thread, you will need to make sure that it runs quickly so that the user interface does not respond. The above approach is used here if you want to see a working example.

See here for more information: Global Event Listeners

And this is for learning: AWT event listener

+3
source

There is a global event dispatcher in java swing that you can use. This basically happens, captures the event, executes its own logic, and sends it to the actual component. For example, if you want 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 information about this here - Event Dispatchers

0
source

All Articles