I have a custom component subclassed from JPanel, with a keyboard handler. My main application embeds this inside another JPanel. Now I want the parent JPanel to also respond to keystrokes, since there are some actions that need to be taken only when the component is focused, but which apply to the app as a whole, and not that component (e.g. when I hit Ctrl-R I want a separate status window to refresh itself, but only when my component has the keyboard focus.)
Right now I’m doing this by explicitly passing my constructor a handler that its KeyListener calls when it’s done, but it would probably be cleaner to use swing’s native way of doing things, if it has one. Is there any support for this sort of handler chaining up a container hierarchy? I’ve looked at the KeyboardFocusManager and the KeyEventHandler, but those seem to be global in scope, whereas I want something restricted to a single container that triggers only when one of its children has the keyboard focus.
You could also try adding a key binder to the component.
Here’s a tutorial that will show you how to use key bindings. Key bindings allow you to assign particular components actions to perform when they have a certain kind of focus, and can be used on any object that extends JComponent. This can be used more widely amongst all JComponent’s and supports different focus types, e.g. when the component solely has the focus or when its window has the focus. Adding and removing a key listener can cause little bugs to creep into your application, especially if the focus listener misfires, so be careful if you choose that route.