Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add global action event listener?

Tags:

java

events

How to add a global action event listener? I've tried

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

but it doesn't work.

like image 568
kofucii Avatar asked Jan 18 '23 12:01

kofucii


2 Answers

(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

like image 79
COD3BOY Avatar answered Jan 21 '23 03:01

COD3BOY


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.

like image 33
Michael Koch Avatar answered Jan 21 '23 02:01

Michael Koch