6

I am an experienced Java programmer, but a Swing newbie so please bear with me.

I wish to have a JPopupWindow which has keyboard focus. I want to respond to arrow keys, escape (to close the menu) and Enter (to invoke the item). Must I add a KeyListener to the menu and code all this myself, or is there some sort of "mode" I can set to activate this behavior which seems like it ought to be standard.

The standard Swing tutorial section on JPopupMenus speaks only of mnemonics and accelerators. I don't particularly want those.

Hard to believe that this is totally against the grain of JPopupMenu.

What is best way to get something like I want implemented?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Steve Cohen
  • 4,679
  • 9
  • 51
  • 89

2 Answers2

6

Once you do jpopupMenu.show(Component invoker, int x, int y)it will automatically respond to keyboard as you want. If this is not working then you might need to fix some other issue i.e some other component is snatching away focus from the menu when it should not etc.

Ashwinee K Jha
  • 9,187
  • 2
  • 25
  • 19
  • hmm. I was using setVisible(true) rather than show() but I see that show() is deprecated in favor of setVisible()/ – Steve Cohen Dec 14 '11 at 16:16
  • I was talking about show(Component invoker, int x, int y) method that I have used in my code. Sorry for confusion. – Ashwinee K Jha Dec 14 '11 at 16:19
  • That is the answer. I wasn't properly tied to a component. Trashgod's reply was also necessary to do that. Thanks to both of you. – Steve Cohen Dec 14 '11 at 18:09
  • Well, I spoke a little too soon. This isn't completely solved, but still 90% pf the way there. Arrow Keys function as desired. Enter key does not make the selection (but space key does) and ESC key does not cancel the menu. – Steve Cohen Dec 14 '11 at 18:35
  • I actually tested and it works fine for me including ESC/ENTER keys. I am just creating JPopupMenu adding few JMenuItems to it and then calling show(myButton, 0, 0) on it. I am creating the popupmenu on clicking the button. – Ashwinee K Jha Dec 14 '11 at 18:42
  • Hmm, possibly those keys are being eaten somewhere else. – Steve Cohen Dec 14 '11 at 18:55
  • Possibly some component is registering key-bindings for these keys even when it is not focussed. Probably http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html may help. – Ashwinee K Jha Dec 14 '11 at 19:01
3

Instead of KeyListener, I'd recommend adding Action instances to your JPopupMenu. Use setComponentPopupMenu() to add the popup to your panel.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045