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
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