Detecting a Keypress

  • Thread starter Mike Westerfield
  • Start date
M

Mike Westerfield

This is an issue that has come up before, but I have yet to see a
satisfactory reply.

Is there any way in Java to implement a general event listener that
sees all of the keyboard events sent to the application? This should
happen regardless of what component (if any) has the focus.

The specific issue I'm trying to deal with is interrupting a
time-consuming task that is operating in another thread.

I would like to do that by wathcing for a keystroke, but I have no way
of knowing which of the hundreds of components in the application
might have the focus when the thread needs to be interrupted. For that
reason, I do _not_ want to attach a listener to a specific component.

Despite that desire, I tried attaching the following handler to a
JPanel that is always open when the thread is running, but it fails in
many situations--even though a component in the JPanel definitely has
the focus when I press Command-esc on a Macintosh.

int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
ActionListener abortListener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
Toolkit.getDefaultToolkit().beep();
}
};
c.registerKeyboardAction(abortListener, "Abort Script",
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, mask),
JComponent.WHEN_IN_FOCUSED_WINDOW);

It doesn't work. Is there something wrong with this approach?

Mike Westerfield
 
A

ak

try to register this action for JRootPane of your
JFrame/JDialog/JWindow/JApplet/JInternalFrame:

frame.getRoolPane().registerKeyboardAction(abortListener, "Abort Script",
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, mask),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

according to javadoc registerKeyboardAction() is now obsolete.
You should use getActionMap() and getInputMap().
see javadoc for details.
 
K

Kleopatra

Mike said:
This is an issue that has come up before, but I have yet to see a
satisfactory reply.

Is there any way in Java to implement a general event listener that
sees all of the keyboard events sent to the application? This should
happen regardless of what component (if any) has the focus.

have a look at KeyEventDispatcher: it will see all keyEvents before the
KeyboardFocusManager and can do with them whatever it likes.

Greetings
Jeanette
 
N

nos

1. what's wrong with using a button?
2. i have seen indication that beep doesn't work on all windows platforms
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top