Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

Key events on application level in Java

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

Answers (3)

Aaron
Aaron

Reputation: 5980

You can add a global event listener to you application using the addAWTEventListener() method in java.awt.Toolkit.

http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener%28java.awt.event.AWTEventListener,%20long%29

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

PhiLho
PhiLho

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

Paul Keeble
Paul Keeble

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

Related Questions