Shortcuts don't work until main component is clicked on

After a couple of missteps and much hair pulling, I’ve finally managed to get my menu bar and ApplicationCommandManager working; all command items of my menu are successfully registered with the command manager and dispatched to the correct target. Same with shortcuts. Except for one snag: right after my app starts up, none of my shortcuts work until I click anywhere in my main component. So I’m assuming it’s a focus issue. I tried to manually grab focus with grabKeyboardFocus() after my app starts up, but that didn’t change anything.

After some detective work, it looks like all the right things are happening when I press a shortcut combo:

  • the correct ApplicationCommandTarget is found by going up the chain via getNextCommandTarget()
  • the target is queried via getCommandInfo() with the correct commandID and successfully sets the ApplicationCommandInfo

But at that point it stops and perform() is never called on the target. Note that selecting a menu item that invokes the same command works, so it must be something about the key mappings. Any ideas?

I am also interested to see what others do to manage keyboard focus on extended hierarchies. I have found my way around these issues by creating my own set of pointers to focus windows, and then invoking commands directly, but this can hardly be the best way to deal with it. What are the best strategies for determining how windows go in and out of focus, and sending commands thereafter?

edit: did you try the setWantsKeyboardFocus() flag as well?

edit 2: looking at the documentation, grabKeyboardFocus() will not work if you call it from within a component’s own constructor. You can only run this command once the Component has been successfully created and added to some other component.

Yep, setWantsKeyboardFocus() sadly didn’t work, either. But adding the key mappings as a KeyListener to the main window (instead of just the main component) did the trick.

1 Like