0

In my Java Swing GUI I have a main window with JMenus and shortcuts, and the possibility to open a second window to see some detail information.

When having clicked somewhere in the the second window, the menu shortcuts no longer work -- of course, it is another window than the one where the menu resides.

How can I "forward" the key events from the second window to the main window? My first idea was to let the main window implement KeyListener and put getJMenuBar().dispatchEvent(...) into the relevant methods, but while thinking about that, I saw lots of Do not use KeyListeners in Swing! statements on SO.

Bowi
  • 1,378
  • 19
  • 33
  • 1
    1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) This seems more a case for [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Feb 09 '17 at 13:36
  • 1
    Use `KeyBinding`s instead, see the answer in this [question](http://stackoverflow.com/q/40944066/2180785) and probably you might want to use `KeyStroke` and `setAccelerator(...)` as shown in the answers for [this question](http://stackoverflow.com/questions/13366793/how-do-you-make-menu-item-jmenuitem-shortcut) for the shortcuts – Frakcool Feb 09 '17 at 13:38
  • 1
    @AndrewThompson I'm so sleepy that I didn't thought about the Card Layout right now... but agree with that – Frakcool Feb 09 '17 at 13:40
  • Use [`Action`](https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) to encapsulate the functionality for use in in multiple views. – trashgod Feb 09 '17 at 16:31
  • Short answer is, don't. Move what ever functionality you need to the currently focused window, as trashgod says, make use of the `Action` API to reduce possible code duplication – MadProgrammer Feb 09 '17 at 20:54
  • Unfortunately, I cannot do anything with the source of the second window. It is a closed-source component. All I can do is calling its public (swing) methods. – Bowi Feb 10 '17 at 08:10

0 Answers0